'Getting 400 error Bad request using axios
I am using axios and getting a 400 bad request error. I am using react-redux and trying to send a post request to localhost:3000/posts. Here is the code that I am using.
import axios from 'axios';
import {
GET_ALL_POSTS,
GET_POST,
CREATE_POST,
DELETE_POST,
UPDATE_POST
} from './types';
const ROOT_URL = 'http://localhost:3000';
export function createPost({content, title}, cb) {
return function(dispatch) {
axios.post(`${ROOT_URL}/posts`, {content, title})
.then((response) => {
console.log(response);
dispatch({
type: CREATE_POST,
payload: response
});
})
.then(() => cb())
.catch((error) => {
console.log("Problem submitting New Post", error);
});
}
}
Solution 1:[1]
i was also getting this error, the issue was not with server or with axios or proxy url.
The issue was i wasn't sending the correct data from my react application.
For Example
i supposed to send:
{ email: '[email protected]', password: 'asdf' }
what i was sending is:
{ name: '[email protected]', password: 'asdf' }
this caused api don't understand name field, as i provided email as the key in api.
so if you are still facing the issue try to check if you are sending the correct data.
Solution 2:[2]
For every post request, the client first sends an OPTIONS request to check whether the server is ready to accept the connection. You should also allow the server to accept options request. If you have not allowed use the below lines in case of node server
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
next();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ibtisam Ur Rehman |
| Solution 2 | sakhib |
