0

编辑:尝试访问我的服务器时出现以下错误:

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

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

反应:

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 有关。

4

3 回答 3

0

您的控制台显示: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 作为参数并进行适当的错误处理。这个问题是错误处理不当的情况。

于 2020-05-04T16:23:07.143 回答
0

您的代码中没有问题(可能);因为请求将被视为SAME-ORIGINif domainport并且protocol请求的来源和目的地都相同;但是您的请求是前往30013000违反同源规则的端口;因此CROSS-ORIGIN;另外两个部分都可以localhosthttp但端口不同;您需要配置您的服务器以正确响应OPTION(飞行前)请求以正确解决此问题;

于 2020-05-04T15:21:08.433 回答
0

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

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

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

于 2020-05-04T15:22:48.090 回答