【问题标题】:fetchAPI not returning response as then() is getting skippedfetch API 不返回响应,因为 then() 被跳过
【发布时间】:2020-05-03 11:30:29
【问题描述】:

我正在使用 fetchAPI 对我的路由器进行后调用,它将获取登录用户的数据。

下面是相同的代码

submit_button.addEventListener('click',getuser)

function getuser()
{
console.log('clicked')

const username=uname_button.value;
const password=age_button.value;
console.log('username'+username)
console.log('password'+password)
 const user = {
    email: username,
    password: password

};
  let options = {
    method: 'post',
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    },
    body: JSON.stringify(user)
  }

fetch('/users', options)
  .then(function(response) {
  console.log(response)
  })

}

当我在浏览器中执行此操作时,数据已成功发布,但未打印响应,甚至没有承诺。 当我添加调试点时,我可以看到控件没有进入 then() 块? 谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript fetch-api


    【解决方案1】:

    在then之后添加一个catch块,看看是否有错误发生,如下:

    fetch('/users', options)
        .then(function(response) { console.log(response) })
        .catch(function(error) { console.log(error) })
    

    【讨论】:

    • 我也添加了catch块,但是从fetch方法中,控制直接结束,忽略then并catch块。
    【解决方案2】:

    请记住,fetch 返回一个包含 Response 对象的 Promise。为了从响应中提取 JSON 正文内容,我们使用 json() 方法。

    fetch('/users', options)
     .then(response => response.json())
     .then(data => console.log(data))
     .catch((error) => {
       console.error('Error:', error);
     });
    

    【讨论】:

    • 添加 catch 块后,现在抛出错误。 TypeError:无法读取未定义的属性“requestContent”。我检查了 myserver,它正在 db 中创建记录,但无法获取响应
    • 试试这个头文件:{ 'Content-Type': 'application/json' }
    猜你喜欢
    • 2019-08-22
    • 2021-02-17
    • 2017-12-05
    • 2017-09-13
    • 2020-04-28
    • 2017-08-28
    • 1970-01-01
    • 2017-03-04
    • 2017-01-25
    相关资源
    最近更新 更多