【问题标题】:I am trying to call an API when submitting a form using Fetch() but facing an error我在使用 Fetch() 提交表单时尝试调用 API,但遇到错误
【发布时间】:2019-02-27 09:08:13
【问题描述】:

问题是

“未处理的拒绝(SyntaxError):输入意外结束”
& CORB(跨域读取阻塞)。

我的代码是

handleSubmit(event){
  event.preventDefault();
  const data = new FormData(event.target);
  fetch('http://api.valios.net/user/signup',
    {
       method:'POST',
       mode:'no-cors',
       headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
      },
        body: data,
    })
    .then(response => response.json()) //handle json response
    .then(responseJson => {
      console.log(responseJson);
    });
}

【问题讨论】:

  • 首先,你应该像function handleSubmit(event)一样声明它。其次,你误用了FormData,看看this answer的正确用法。解决这些问题并首先编辑您的问题,否则您的问题将无法正确复制。

标签: reactjs fetch


【解决方案1】:

您将 no-cors 和 Cross origin 的标头放在一起,您可以按如下方式更改您的代码

handleSubmit(event){
event.preventDefault();
const data = new FormData(event.target);
fetch('http://api.valios.net/user/signup',
{
   method:'POST',
   mode:'cors',
   headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*"
  },
    body: data,
})
  .then(response => response.json()) //handle json response
  .then(responseJson => {
    console.log(responseJson);
  });
}

问候

【讨论】:

    猜你喜欢
    • 2019-10-09
    • 2018-10-25
    • 2011-12-23
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2021-03-28
    相关资源
    最近更新 更多