0

I am trying to connect to a third party endpoint from my express app. With specific body Doing the same request in curl directly to that endpoint gives me a 400 status with a specific error message.

Now using express + node-fetch, I am getting the error message, but I get 200 status code.

export async function authenticate() {
  const result =  await fetch(`${config.host}/token`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: JSON.stringify({
        key: "someValueThatShouldReturnError"
    })
  });
  console.log(result.status); // this prints 400
  const json = await result.json();
  return json;
}

And in the router I have

router.post('/auth', handleErrorAsync(async(req: any, resp: Response, err: any) => {
  let res = await authenticate();
  resp.send(res);
}));

a temporary solution is to add this in the async function after declaring json variable..But I feel this should be handled out of the box.

  if (result.status !== 200) {
    throw createError(result.status, json.error);
  }
AngularDebutant
  • 1,436
  • 5
  • 19
  • 41
  • `resp.status(res.status).send(res)` [reference](https://expressjs.com/en/api.html#res.status) – MAS Oct 14 '20 at 08:33
  • what is the purpose of this line ` const json = await result.json(); ` – MAS Oct 14 '20 at 08:35
  • @MAS to convert the response from server to JSON. Without it I get a response `{ "size": 0, "timeout": 0 }` – AngularDebutant Oct 14 '20 at 08:44
  • try this, `const status = result.status; const json = await result.json();` then return both values; `return {status , json}`, `const { json, status } = await authenticate();` – MAS Oct 14 '20 at 09:05
  • @MAS yes this works, but shouldnt express handle this automatically? :O – AngularDebutant Oct 14 '20 at 09:11
  • Express is just a mean to help to communicate through HTTP, it doesn't know the business logic we are handling, error or success, we have to handle that ourselves – MAS Oct 14 '20 at 10:29

0 Answers0