neeraj mdas
neeraj mdas

Reputation: 183

Axios library failing to respond for post request, trying with curl and postman works

Below is the following code I am using to access a remote server:

axios({
    method: 'post',
    url: 'SERVER URI',
    data: {"key1": "val1","key2": "val2"},
    headers: {
        'Authorization': 'Bearer ${token}',
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    }
})
.then((res) => {
    console.log('Response **', res);
    resolve(res.data);
}).catch(err => {
    console.log('Error from server is ***', err.response);
    reject(err.response.data);
});

here token is an oauth2 bearer token using client credentials as grant-type. I am getting a 404 response for this with data: {message: ''}. But I tried the same in postman as well as with a curl request. For both these instances, I got back a valid 200 response.

I am attaching the curl request also,

curl --location --request POST 'URI' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer TOKEN' \
--header 'Content-Type: application/json' \
--data-raw '{"key1": "val1","key2": "val2"}'

I may be overlooking something but I am going crazy as to not understanding what I am missing. Any help for this is appreciated

Upvotes: 1

Views: 400

Answers (2)

evanhsu
evanhsu

Reputation: 323

A 404 response makes me think that maybe the url has a typo in it, but I have seen APIs that respond with 404 as a security measure when authorization fails so it could be a bad Authorization header, too.

There's a typo in the code sample from the original question:

headers: {
    'Authorization': 'Bearer ${token}',
    ...
}

the single quotes surrounding the Bearer ${token} would need to be changed to backticks in order for the template string to actually be expanded. As it is now, the Authorization header is actually being sent with the literal string ${token} as your token.

Upvotes: 0

Junior Tiemele
Junior Tiemele

Reputation: 1

You can try to use formData like that:

const data = new FormData()
data.append('key1', 'val1')
data.append('key2', 'val2')
axios({
method: 'post',
url: 'SERVER URI',
data: data,
headers: {
    'Authorization': 'Bearer ${token}',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
}
})

    .then((res) => {
        console.log('Response **', res);
        resolve(res.data);
    }).catch(err => {
        console.log('Error from server is ***', err.response);
        reject(err.response.data);
    });

Upvotes: 0

Related Questions