json 无法使用fetch获取资源,NetworkError

evrscar2  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(124)

我正在使用这个从我的API获取数据。它将向我的API发布电子邮件和密码:

  1. onSubmitSignIn = () => {
  2. fetch('http://localhost:3001/signin', {
  3. method: 'post',
  4. headers: {'Content-Type': 'application/json'},
  5. body: JSON.stringify({
  6. email: this.state.signInEmail,
  7. password: this.state.signInPassword
  8. })
  9. })
  10. .then(response => response.json())
  11. .then(data => {
  12. if (data === 'login success') {
  13. this.props.onRouteChange('home');
  14. }
  15. })
  16. .catch((e) => console.log(e))
  17. };

字符串
并且请求将在API中由此

  1. app.post('/signin', (req, res) => {
  2. if (req.body.email === db.users[0].email && req.body.password === db.users[0].password) {
  3. res.json('login success')
  4. } else {
  5. res.json('login fail')
  6. }
  7. });


这将导致:
TypeError:尝试获取资源时发生NetworkError。
但是,如果删除.then并在下面添加this.props.onRouteChange('home');,如下所示

  1. onSubmitSignIn = () => {
  2. fetch('http://localhost:3001/signin', {
  3. method: 'post',
  4. headers: {'Content-Type': 'application/json'},
  5. body: JSON.stringify({
  6. email: this.state.signInEmail,
  7. password: this.state.signInPassword
  8. })
  9. })
  10. this.props.onRouteChange('home');
  11. };


它将工作,我可以登录没有错误。
但是,如果像这样删除this.props.onRouteChange('home');,仍然会显示相同的错误

  1. onSubmitSignIn = () => {
  2. fetch('http://localhost:3001/signin', {
  3. method: 'post',
  4. headers: {'Content-Type': 'application/json'},
  5. body: JSON.stringify({
  6. email: this.state.signInEmail,
  7. password: this.state.signInPassword
  8. })
  9. })
  10. };


我还用Postman仔细检查了我的API,post请求成功了。
这对我来说是个奇怪的问题,我是JavaScript的新手,如果这是一个粗心的新手错误,请原谅我。
P.S.如果需要更多代码,请告诉我。

vhmi4jdf

vhmi4jdf1#

您是否在托管应用程序的同一客户端上运行应用程序?尝试将localhost更改为客户端的LAN IP,看看是否有区别?

相关问题