Getting 400 error Bad request using axios

若如初见. 提交于 2020-01-24 06:27:08

问题


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);
      });
  }
}

回答1:


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();
});



回答2:


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: 'ib2@gmail.com', password: 'asdf' }

what i was sending is: { name: 'ib2@gmail.com', 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.



来源:https://stackoverflow.com/questions/44731340/getting-400-error-bad-request-using-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!