我正在使用这个从我的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。
但是,如果删除.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,post请求成功了。
这对我来说是个奇怪的问题,我是JavaScript的新手,如果这是一个粗心的新手错误,请原谅我。
P.S.如果需要更多代码,请告诉我。
1条答案
按热度按时间vhmi4jdf1#
您是否在托管应用程序的同一客户端上运行应用程序?尝试将localhost更改为客户端的LAN IP,看看是否有区别?