【问题标题】:Axios post request from react results in empty or weird body来自 react 的 Axios 发布请求导致正文为空或奇怪
【发布时间】:2019-01-12 17:28:45
【问题描述】:

正在开发我的第一个 MERN 堆栈应用程序。我正在尝试从我的 React 客户端(端口 3000)向我的 MongoDB API(端口 3001)发出 axios 发布请求。我的帖子请求代码是:

<button
        onClick={() => {
          axios({
            method: "post",
            url:
              "http://localhost:3000/api/update/documentID",
            data: { newNumber: 12345 },
            headers: { "Content-Type": "application/x-www-form-urlencoded" }
          });
        }}
      >
        Click to run axios post request
</button>

这导致我的 3001 端口服务器上显示的正文为:

body: { '{"newNumber":12345}': '' }

我在我的端口 3001 服务器上设置了我的 React 代理服务器和 body-parser。我可以使用 Postman 提出我想要的确切请求。我也可以通过将 React 中的 Button 替换为 Form 来获得我想要的东西,但显然必须提交一个表单来发出 post 请求并不理想。

(另外,如果我尝试使用 axios.post(etc) 而不是 axios({ method: post, etc.),我最终会得到一个完全空的正文。

任何帮助将不胜感激。

【问题讨论】:

  • 警告:如果您使用的是 Postman,请确保请求已正确设置 Content-Type: application/json 并在“正文”选项卡中使用 raw 格式而不是 @987654326 @.

标签: axios


【解决方案1】:

回答了我自己的问题,改变了

headers: { "Content-Type": "application/x-www-form-urlencoded" }

headers: { "Content-Type": "application/json" }

它成功了。

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2018-03-22
    • 1970-01-01
    • 2021-11-21
    • 2013-07-21
    相关资源
    最近更新 更多