【问题标题】:Is there any proper way to send a POST request through React using fetch()?是否有任何正确的方法可以使用 fetch() 通过 React 发送 POST 请求?
【发布时间】:2021-08-04 01:21:32
【问题描述】:

我在 API 服务器端将 url 设为 None,并且在使用 POSTMAN 和其他脚本进行测试时 API 工作正常,但 在 React 中发送请求时会出现问题.

const imgLoad = {
  method: 'POST',
  headers: {
    "Content-Type":"application/json"
  },
  body: JSON.stringify({
    image_url: imageurl    //image url stored in a variable & I tried using a string but the problem is still there
  })
}

fetch("http://127.0.0.1:7000/emotion_detection/detect/", imgLoad)
  .then(response => response.json())
  .then(data => this.setState({emotion: data}));

【问题讨论】:

  • 你遇到了什么错误?
  • 不是报错,只是API服务器端image_url的值变成了None,所以是我发送请求的方式有问题。

标签: javascript reactjs django api


【解决方案1】:

使用 POSTMAN 工具从 ReactJS 中找到正确的实现方式。

var formdata = new FormData();
formdata.append("image_url", `${this.state.input}`);

var requestOptions = {
  method: 'POST',
  body: formdata,
  redirect: 'follow'
};

fetch("http://127.0.0.1:7000/emotion_detection/detect/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

【讨论】:

    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多