【发布时间】:2018-06-15 06:07:30
【问题描述】:
我正在使用它从我的 API 中获取数据。它会将电子邮件和密码发布到我的 API
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
.then(response => response.json())
.then(data => {
if (data === 'login success') {
this.props.onRouteChange('home');
}
})
.catch((e) => console.log(e))
};
这个请求会在API中处理
app.post('/signin', (req, res) => {
if (req.body.email === db.users[0].email && req.body.password === db.users[0].password) {
res.json('login success')
} else {
res.json('login fail')
}
});
这将导致TypeError: NetworkError when attempting to fetch resource.
但是,如果 .then 被删除,this.props.onRouteChange('home'); 像这样添加到下面
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
this.props.onRouteChange('home');
};
它会工作,我可以正确登录。
但是,如果像这样删除this.props.onRouteChange('home');,仍然会显示相同的错误
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
};
我还用 Postman 仔细检查了我的 API,发帖请求成功。
这对我来说是一个奇怪的问题,而且我是 javascript 新手,如果这恰好是一个粗心的新手错误,请原谅我。谢谢。
附:如果需要更多代码,请告诉我。
【问题讨论】:
-
@evayly 不太可能。如果我将
this.props.onRouteChange('home');放在fetch下方,我仍然可以登录(参见代码块 3),更不用说我安装了 cors 包。 -
你能在测试html文件中正确执行请求吗
-
是的。但前提是我像在代码块 3 中那样做。
-
代码块 3 不做任何事情,如果抛出它也不会捕获错误
标签: javascript json node.js api fetch