【问题标题】:React Cors issue with ExpressJSExpressJS 的 React Cors 问题
【发布时间】:2020-08-19 01:35:58
【问题描述】:

编辑:我在尝试访问我的服务器时收到以下错误:

POST http://localhost:3001/user/login500(内部服务器错误)

我不确定我哪里出错了,这个错误会继续发生:

反应:

export default class Account extends React.Component {
constructor() {
    super();
    this.state = {
      isLoggedIn: false,
    };
    this.login = this.login.bind(this);
  }
  componentDidMount() {
    const cookies = new Cookies();
    const user = cookies.get('user');
    const pass = cookies.get('pass');
      this.setState({processing: true})
      fetch('http://localhost:3001/user/login', {
        credentials : 'omit',
        method      : 'POST',
        body : JSON.stringify({
          username : user,
          password : pass
        })
      })
      .then(res  => res.json())
      .then(json => {

        // If the login was successful
        if (json.success) {
          this.setState ({
            isLoggedIn: true
          })
        }

        // Otherwise
        else {
          this.setState({
            errorMessage: 'Invalid username or password',
            processing  : false
          });
        }

      })
      .catch(() => {
        this.setState({
          errorMessage: 'An unknown error occurred',
          processing  : false
        });
      });
  }
render() {
  if(this.state.isLoggedIn) {
    return (<p> Logged In</p>);
  }
  else {
    return (<p> Not Logged In</p>);
  }
}}

快递:

router.post('/login', (req, res) => {

  return User
    .findOne({username: req.body.username})
    .then (user => user.authenticate(req.body.password))
    .then (auth => {
      if (auth.user !== false) {
        req.session.user = auth.user.user
      }
      res.json({success: auth.user !== false})
    })
    .catch(() => res
      .status(500)
      .json({success: false})
    );
});

这个错误没有提供太多关于我可能做错的信息,但它可能与 cors 有关。

【问题讨论】:

  • @AtinSingh 我看到了这个,但是如果我使用 cors 包,我会收到以下错误:POST http://localhost:3001/user/login net::ERR_CONNECTION_REFUSED
  • .catch((err) =&gt; res //add err here and console.log .status(500) .json({success: false}) ); 你能做到这一点并告诉我们结果吗?如果 err 太大,您可以告诉我们相关部分。 (可能在 err.response.data 中)
  • 我的控制台显示:Cannot read property 'authenticate' of null

标签: reactjs express cors


【解决方案1】:

您的控制台显示:Cannot read property 'authenticate' of null

在你的 .catch 的 api -

.catch(() => res
  .status(500) // you are sending 500 (internal server error) irrespective of what your actual error is//
  .json({success: false})
);

你的错误是 -

  return User
    .findOne({username: req.body.username})
    .then (user => user.authenticate(req.body.password)) //can read authenticate of null because user is null i.e This user does not exist in your DB. //

我建议在你的 catch 块中添加 err 作为参数并进行适当的错误处理。这个问题是错误处理不当的情况。

【讨论】:

  • 我输入的用户名确实存在于数据库中
  • @Shauna 您需要确保您正在搜索正确的密钥,因为根据错误,您的 findOne 没有返回任何用户。检查这是否正确{username: req.body.username}
  • 这似乎不正确,但我看到的任何例子都表明它是正确的。
  • @Shauna 你在用猫鼬吗?
  • 我正在使用 Mongoose,是的,我的 app.js 文件中有此连接
【解决方案2】:

您是否在package.json 中添加了proxy 参数?我经常使用此设置,但没有看到您看到的问题。尝试将以下参数添加到package.json

{
  "name": "mern",
  "version": "0.1.0",
  "proxy": "http://localhost:3001/"
...
}

然后您的所有 API 调用都可以只是 /api,因为代理参数已设置。

【讨论】:

  • 我现在对其进行了编辑,以显示我正在做的事情,因为我现在正在使用 cors 包。使用 cors 包时我还应该将它添加到 package.json 吗?
  • @Shauna 不,他的解决方案与此不同,它在开箱即用的 create-react-app 中得到支持;这将解决您的开发问题
【解决方案3】:

你的代码没有问题(可能);因为如果domainportprotocol 在请求的源和目标中都相同,则请求将被视为SAME-ORIGIN;但是您的请求是指向端口3001 而不是3000,这违反了同源规则;因此CROSS-ORIGIN;另外两个部分都可以,在localhosthttp 上,但端口不同;您需要配置您的服务器以正确响应 OPTION(pre flight) 请求以正确解决此问题;

【讨论】:

  • 我现在正在使用 cors 包并对其进行了编辑以显示我现在的错误,但不知道如何解决它
猜你喜欢
  • 2020-05-29
  • 2018-04-04
  • 2021-07-25
  • 2021-02-04
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多