How to make a HTTP post request like a HTML form using Axios?

Viewed 464

I am trying to connect to an API (nova.astrometry.net) that requires an HTTP post request just like a form (x-www-form-encoded). I am using Axios for that, but still, I am getting this error as a response from the API { status: 'error', errormessage: 'no json' }

Here's the code for reference

axios({
    method: 'post',
    url: 'http://nova.astrometry.net/api/login',
    data: {
        'request-json': JSON.stringify({ "apikey": process.env.API_KEY })
    },
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
}).then((response) => {
    console.log(response.data)
});

I also tried using the request library but got the same response.

1 Answers

The content type required by the api is 'application/x-www-form-urlencoded' but you are sending 'application/json'.

To send that data, do the following:

const body = new URLSearchParams();
body.append('request-json', JSON.stringify({ "apikey": process.env.API_KEY }));

Then use the above body in the body field of axios.

axios.post('http://nova.astrometry.net/api/login', body, {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .then(res => console.log(res.body))
  .catch(console.error);
Related