Error: Request failed with status code 422 in javaScript - javascript

I am using JS axios. I do not understand this error.
error:
Error: Request failed with status code 422
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
This is my code:
const config = {
headers: { Authorization: `Bearer ${localStorage.getItem('id_token')}`,
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}
}
};
const bodyParameters = {
password:values.newPassword
};
setIsLoading(true)
//localhost:5000/api/v1/user/updatepassword
Axios.post('http://127.0.0.1:5000/api/v1/user/updatepassword',
bodyParameters,
config
)
And I am testing with fetch in chrome console. and got this error:
SyntaxError: Unexpected Identifier

I think your error is use 2 headers in config object. You can write it like this:
const config = {
headers: {
Authorization: `Bearer ${localStorage.getItem('id_token')}`,
'Content-Type': 'application/json'
}
}

422 status code means that your backend understands your request, but can't process the body (data) you sent.
You can try:
const config = {
method: 'post',
url: 'http://127.0.0.1:5000/api/v1/user/updatepassword',
headers: {
Authorization: `Bearer ${localStorage.getItem('id_token')}`,
'Content-Type': 'application/json'
},
body: {
password:values.newPassword
}
}
axios(config).then(response => console.log(response)).catch(err => console.error(err))
If you get the same error, check your backend gets all the fields it needs.
One more thing you can do: Try making the request on Postman and when it works you can get the axios code for it directly in the code section.

Related

Trying to use fetch instead of axios to make a POST request, but the response from the fetch request returns an error, whereas axios doesn't

I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});

GetResponse 400 Bad Request

I'm trying to send a POST method to https://api.getresponse.com/v3/contacts from my Vue using axios. I'm unsure why I kept getting a 400 Bad Request. I've tried checking the Network tab on Mozilla dev tools but there doesn't seem to have any Response message it just returned me.
XHR OPTIONS https://api.getresponse.com/v3/contacts [HTTP/1.1 400 Bad Request 763ms]
I have double confirm from GetResponse documentation to add the Content-Type header to application/json and to set my API key as X-Auth-Token: api-key <API_KEY>.
NOTE: I am also getting CORS header ‘Access-Control-Allow-Origin’ missing but I believe it does not have anything to do with the Error 400.
Here are some code snippets from my Vue file.
axios-config.js
const instance = axios.create({
baseURL: process.env.VUE_APP_GET_RESPONSE_BASE_URL,
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': `api-key ${process.env.VUE_APP_GET_RESPONSE_API_KEY}`,
}
});
Vue
import axios from "#/services/axios-config.js";
user: {
name: "",
campaign: {
campaignId: `${process.env.VUE_APP_GET_RESPONSE_CAMPAIGN_ID}`
},
email: "",
customFieldValue: {
customFieldId: "interest",
value: []
}
}
async callSubscribeAPI() {
try{
const response = await axios.post("/contacts",this.user);
console.log(response);
}catch(error){
console.log("error");
console.log(error);
}
}
This works for me:
(async() => {
const url = 'https://api.getresponse.com/v3/accounts';
const payload = await axios({
method: 'get',
url,
headers: {
"X-Auth-Token": "api-key 12345*****",
"content-type": "application/json"
}
});
console.log("payload", payload.data);
})()

using http with axios return 400 with request it works

I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.

npm start gets 401 and node app.js gets 200 response

I have a React project that I run with npm start and this code gets 401 Error from the second fetch (the first one is ok). It runs fine returning 200 only with node, like in "node App.js".
So what would I need to do to run my React project getting 200 response? Why is there this difference between npm and node to this request response?
const clientID = <ClientID>
const clientSecret = <ClientSecret>
const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${encode}`,
},
};
fetch("https://auth-nato.auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials", requestOptions)
.then(response => { return response.json() })
.then(data => {
const requestOptions2 = {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json',
'Authorization': `Bearer ${data.access_token}`
},
body: '{"username":"Ana", "password":"test123","user_id":"ana#email.com"}'
};
fetch('https://j1r07lanr6.execute-api.sa-east-1.amazonaws.com/v1/register', requestOptions2)
.then(response => {console.log(response)});
})
Buffer - is not presented in the browser's javascript.
Instead of
const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')
use just
const encode = btoa(`${clientID}:${clientSecret}`);
Read more about base64 encoding on MDN.
I found out it was a CORS issue that needed to be set correctly on the back-end. My workaround was disabling chrome web security and removing "mode: no-cors".
I've tried adding "Access-Control-Allow-Origin":"http://localhost:3000" to headers but it doesn't work.

npm request send token and header 'content-type': 'application/json' at the same time

I'm trying to get a response back from an API by sending the token and the header 'content-type': 'application/json', but I don't know where should I put them.
This is my code so far:
var request = require('request');
request.get('google example url', {
//
'auth': {
'bearer': '15252727282'
},
"headers": {
"Content-Type": "application/json"
}
}, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body);
});
This is what I'm getting back in my console:
error: null
statusCode: 401
body: HTTP Token: Access denied.
OK I did it using options as the first parameter and with the following lines:
const options = {
url: 'target url',
method: 'GET',
headers: {
"Authorization": "Token token=12425262",
"Content-type": "application/json"
}
};
request(options, function(err, res, body) {
let json = JSON.parse(body);
console.log(json);
});
You're getting that error because you have never defined require anywhere on your client-side.
Add this to your project: http://requirejs.org/docs/release/2.2.0/minified/require.js
If you want to use require on the client take a look at this http://requirejs.org/.

Categories

Resources