【问题标题】:Fetch api for post not working为帖子获取 api 不起作用
【发布时间】:2018-03-03 16:50:54
【问题描述】:

我正在尝试使用 Fetch-api 在 reactjs 中运行 post api。

我尝试在邮递员上运行相同的 API,它运行了。

我不知道我错过了什么。

我正在使用的代码。

fetch('url', { 
            method: 'POST',
            mode: "no-cors", // or without this line
            redirect: 'follow',        
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
              },
            body: {
                "username": this.state.user_name,
                "password": this.state.password
            }
        })

在上面的代码中,我收到 500 Internal server error

如果我使用 Json.stringyfy 在正文中会出错content-type。我需要将内容类型发送为 json-application

如果还有其他发送 POST 请求的方法,也请告诉我。

谢谢..:)

【问题讨论】:

  • 你在 fetch 调用中有一个真正的“url”吗?
  • 其实它是在本地网络上配置的..但它在邮递员上工作..
  • this.state.user_namethis.state.password 的值是多少?试试body: JSON.stringify({ username: this.state.user_name, password: this.state.password })
  • @bennygenel 是的,我使用了这个 JSON.stringify({ username: this.state.user_name, password: this.state.password }) 。但当时内容类型更改为文本。但实际上我需要 application-json。
  • 更改为文本是什么意思?您仍然可以通过 header 属性设置 Content-Type。

标签: json reactjs fetch-api


【解决方案1】:

您是否尝试过使用Axios

例子:

axios.post('url', {
    username: 'Fred',
    password: 'xyz'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

【讨论】:

  • 我使用 npm 安装 axios。但我得到 axios is undefined 错误。是否需要从任何地方导入。
  • 需要在使用的组件中导入。
  • 现在,我收到这样的错误“无效 CORS 请求”。所以这是 CORS 错误。
  • 您可以访问服务器吗?您需要允许 CORS 请求。
  • 是的,其实是在邮递员那里工作,所以,应该在这里工作...
猜你喜欢
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 2018-12-15
  • 2018-12-04
  • 1970-01-01
相关资源
最近更新 更多