I am saving data to mongodb with create function, after successfully data saved to database, i am sending message with 302 status code. But axios going in catch function instead of then function. And response is undefined.But when i see the response in.network tab.I am getting the response.Below is my code.
saving data in mongodb
exports.addProject = async (req, res) => {
Project.create(req.body)
.then(function(){
res.status(302).send({message: MESSAGE.PROJECT_ADDED_SUCCESS})
})
.catch(err => handleErrors(res, err));
};
At fronend, in axios, while getting response
export function addProject(data) {
const token = localStorage.getItem(CONFIG.AUTH_TOKEN);
const url = `${CONFIG.API_BASE_URL}/api/projects`;
axios.post(url, data, { headers:{ Authorization:`${token}`}}).then(function(response){
console.log(response);
return response;
})
.catch(function(response){
console.log(response);
return response;
})
}
Please tell me how can i get response in axios request then function. Below is the attached error image.
You can use the option validateStatus
This is the default value
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}
You can add your custom, for allow
validateStatus: function (status) {
return status >= 200 && status <= 302
}
If you want simply to get a response with the created resource you may use 200 Success
or 201 Created
status. If you want to process 302 Found
somehow, you should create your own handler in catch()
section and also send Location
header because status 302 Found
means:
"The content you were looking for exists but in a different location"
For more info on this topic regarding axios you can read here .
This solved the issue.
Try with this example:
result = await axios.get(url, {
validateStatus: function (status) {
// if this function returns true, exception is not thrown, so
// in simplest case just return true to handle status checks externally.
return true;
}
});
if (result.status === 302) {
// GET YOUR RESPONSE HERE
console.log(result.data);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.