使用 axios 获取 400 错误错误请求 [英] Getting 400 error Bad request using axios

查看:188
本文介绍了使用 axios 获取 400 错误错误请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 axios 并收到 400 个错误的请求错误.我正在使用 react-redux 并尝试向 localhost:3000/posts 发送 post 请求.这是我正在使用的代码.

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

推荐答案

对于每个 post 请求,客户端首先发送一个 OPTIONS 请求来检查服务器是否准备好接受连接.您还应该允许服务器接受选项请求.如果您不允许在节点服务器的情况下使用以下行

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

这篇关于使用 axios 获取 400 错误错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆