【问题标题】:Cant fetch simple string无法获取简单的字符串
【发布时间】:2021-10-26 20:11:40
【问题描述】:

我想下载一个简单的字符串到服务器,但服务器没有响应。当我通过邮递员尝试时它工作正常,但是当通过我的代码时没有收到回复。 当我删除 haeder“内容类型”时,控制台返回一个空对象 {}

我得到了控制台的响应。

const downloadHandler = (e) => {
e.preventDefault();
  fetch("http://localhost:8080/download", {
    method: "POST",
    mode: 'no-cors',
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({name: "test"}),
  })
}

还有一些节点

app.post('/download', function(req, res) {
 console.log(req.body)
 res.json(req.body)
 })

【问题讨论】:

  • 尝试从前端代码中删除“no-cors”,并添加 app.use(cors()) 中间件,如果还没有使用,也不要忘记使用 express.json 中间件。
  • 在我的情况下删除和添加 cors 到后端有帮助。感谢

标签: node.js reactjs


【解决方案1】:

fetch 返回一个Promise,所以你应该使用async await
另外,删除 no-cors 属性。

尝试像这样更改您的代码:

const downloadHandler = async (e) => {
  e.preventDefault();
  try {
    const response = await fetch('http://localhost:8080/download', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: 'test' }),
    });
    const data = await response.json()
    console.log(data)
  } catch (err) {
    console.log(err);
  }
};

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多