【问题标题】:Unable to fetch resource with fetch, NetworkError无法使用 fetch 获取资源,NetworkError
【发布时间】: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


【解决方案1】:

您是否在托管该应用的同一客户端上运行该应用?尝试将 localhost 更改为您客户端的 LAN IP,看看是否会有所不同?

【讨论】:

  • 无变化。我在192.168.1.1:3000 上运行应用程序,在192.168.1.1:3001 上运行API。
猜你喜欢
  • 2021-07-30
  • 2019-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2022-06-30
  • 1970-01-01
相关资源
最近更新 更多