Javascript 反应获取调用状态无内容
我试过这段代码:Javascript 反应获取调用状态无内容,javascript,reactjs,fetch,Javascript,Reactjs,Fetch,我试过这段代码: fetch("http://localhost:5000/api/signin", { method: "post", headers: { "Content-Type": "application/json", Authorization: "this-can-be-anything" }, body: JSON.stringify({ email: this.state.email, password: this.state.
fetch("http://localhost:5000/api/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "this-can-be-anything"
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then(response => {
console.log(response);
response.json();
})
.then(data => {
console.log(data);
});
这是一个尝试,看看是否一切都是好的,如果我尝试邮递员呼吁一切工作,在这里也一样,但我没有得到任何回报。我在网络选项卡上得到一个调用,该调用获取我所需的数据,另一个从线路上得到的调用状态为204
没有内容,为什么?您没有返回response.json返回的承诺,因此您的承诺链已断开,未定义将作为最后一个函数的参数提供 添加return关键字,它将按预期工作
fetch("http://localhost:5000/api/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "this-can-be-anything"
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
});
出现此问题是因为您没有从中返回任何内容
.then(response => {
console.log(response);
response.json();
})
如果向箭头函数添加大括号;然后您需要添加一个显式返回。因此,将其更改为:
.then(() => response.json())
或
它应该会起作用。看起来您需要返回.json返回的承诺 使用现代ES7的async/await特性可以稍微解决这个问题,避免无处不在的回调地狱
const loginUser = async () => {
const response = await fetch("http://localhost:5000/api/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "this-can-be-anything"
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
const data = await response.json();
console.log('[data]', data);
return data;
}
const loginUser = async () => {
const response = await fetch("http://localhost:5000/api/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "this-can-be-anything"
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
const data = await response.json();
console.log('[data]', data);
return data;
}