Postman POST works, but not with axis

442 Views Asked by At

Making a post request via insomnia/postman works, gives me the correct response. However, in axios, I can't seem to make it work.

It doesn't give me an error, its a status 200, but doesn't actually login like postman/insomnia does. I feel something is wrong with my axios setup

enter image description here

enter image description here

  const { email, password } = req.body.params
  const endpoint = `https://xxxxxxxxx.com/account/login/`

  try {
    const response = await axios({
      method: 'post',
      url: endpoint,
      data: qs.stringify({
        'customer[email]': email,
        'customer[password]': password,
        'form_type': 'customer_login'
      }),
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      }
    })
    res.status(200).send(response.data)
  } catch (error) {
    res.status(500).send(error)
  }
2

There are 2 best solutions below

0
On

There are 2 solutions (I hope) :

1/ Following this post, you should probably use withCredentials like this :

  const { email, password } = req.body.params
  const endpoint = `https://xxxxxxxxx.com/account/login/`

  axios.defaults.withCredentials = true;

  try {
      (...)
  }

2/ Following this article, you need to set your Content-Type header to application/json so the data is automatically parsed :

Axios also sets the Content-Type header to application/json. This enables web frameworks to automatically parse the data.

0
On

Postman lets you generate the code necessary to recreate your request using axios.

More information on that here: https://learning.postman.com/docs/sending-requests/generate-code-snippets/

Click the code icon to the right of Postman

Postman code button

Then set the code snippet language to NodeJS - Axios and you'll have the exact code necessary to recreate the request. Axios code snippet