Javascript fetchAPI未返回响应,因为正在跳过then()
我正在使用fetchAPI对我的路由器进行post调用,该调用将获取登录用户的数据 下面是相同的代码Javascript fetchAPI未返回响应,因为正在跳过then(),javascript,fetch-api,Javascript,Fetch Api,我正在使用fetchAPI对我的路由器进行post调用,该调用将获取登录用户的数据 下面是相同的代码 submit_button.addEventListener('click',getuser) function getuser() { console.log('clicked') const username=uname_button.value; const password=age_button.value; console.log('username'+username) cons
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()块?
有人能帮我解决这个问题吗?然后添加一个catch块,看看是否发生了错误,如下所示:
fetch('/users', options)
.then(function(response) { console.log(response) })
.catch(function(error) { console.log(error) })
记住,fetch返回一个包含响应对象的承诺。为了从响应中提取JSON正文内容,我们使用JSON()方法
我也添加了catch块,但从fetch方法中,控件将直接结束忽略然后和catch块。添加catch块后,它现在抛出下面的错误。TypeError:无法读取未定义的属性“requestContent”。我已经检查了myserver,它正在数据库中创建一条记录,但无法获取具有以下标题的响应:{“Content Type”:“application/json”}
fetch('/users', options)
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});