用ExpressJS反应Cors问题

时间:2020-05-04 15:07:05

标签: reactjs express cors

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

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

3 个答案:

答案 0 :(得分:0)

您的代码中没有问题(可能是);因为如果SAME-ORIGINdomainport在请求的源和目标上都相同,则该请求将被视为protocol;但是您的请求将转到端口3001而不是3000,这违反了同源规则;因此CROSS-ORIGIN;其他两个部分都可以,分别在localhosthttp上,但是端口不同;您需要配置服务器以正确响应OPTION(飞行前)请求以正确解决此问题;

答案 1 :(得分:0)

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

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

然后所有的API调用都可以是/api,因为已经设置了proxy参数。

答案 2 :(得分:0)

您的控制台显示:response = request.response #gets the full response body of a page and saves to response puts response.code # prints the http response code parameters = response.body.split(" ").grep(/name=/) #split the response into an array and grep for anything with name= parameters.each do |x| x = parameters.to_s.match(/(?<=\\\").*?(?=\\")/i) #converts array to string and performs regex match() puts x end

在您的api中-

parameters.each do |x| 
    puts x.match(/(?<=\\\").*?(?=\\")/i)          #converts array to string and performs regex match()

您的错误是-

i, i1, i2, i3, i4, ...

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