简体   繁体   English

XHR加载失败:AJAX请求上的POST(在React中)

[英]XHR failed loading: POST on AJAX request (in React)

I don't think React has anything to do with this, but just in case, that's what I'm working in. I'm receiving the error XHR failed loading: POST when submitting an AJAX request to /login. 我不认为React与这有任何关系,但是以防万一,这就是我正在工作的内容。我收到错误XHR failed loading: POST向/ login提交AJAX请求时XHR failed loading: POST I am trying to create a login route using Passport JS, and I know that the route is receiving the data because it will console.log as { email: 'myemail', password: 'mypassword' } and typeof returns object. 我正在尝试使用Passport JS创建登录路由,并且我知道该路由正在接收数据,因为它将以console.log作为{ email: 'myemail', password: 'mypassword' }typeof返回对象。

this.handleLoginSubmit = () => {
  let xml = new XMLHttpRequest();

  xml.open("POST", "/login", true);
  xml.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  xml.send(JSON.stringify({email: this.state.email, password: this.state.password}));

  xml.onreadystatechange = () => {
    if(xml.readyState === 4) {
      console.log('here')
      console.log(xml.response);
    }
  }
}

EDIT Here is the route: 编辑这是路线:

router.post('/login', emailToLowerCase, function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
  console.log('error')
  return next(err);
}
if (!user) {
  return console.log('no user!')
}
req.logIn(user, function(err) {
  if (err) return next(err);
  console.log('logging in')
  return res.send(req.user)
});
})(req, res, next);
});

EDIT Here is the form: 编辑这是表格:

<form id='login-form' className="small-form" className='nav-div' onSubmit={props.handleLoginSubmit}>
<div className='nav-div'>
  <li className="nav-item">
      <input type="email" required name="email" placeholder='Email' className='form-control' value={props.email} onChange={(e) => props.handleEmailChange(e.target.value)}/>
  </li>
  <li className="nav-item">
      <input type="password" required name="password" placeholder='Password' className='form-control' value={props.password} onChange={(e) => props.handlePasswordChange(e.target.value)}/>
  </li>
  <li className='nav-item'>
      <input type='submit' value='Login' />
  </li>
</div>

In your code: 在您的代码中:

if (!user) {
  return console.log('no user!')
}

You are not sending any response to UI. 您没有向UI发送任何响应。 Not sure how the next(err) processes the response, but at lease in case user is not found you want to send some error back to the client, like: 不确定next(err)如何处理响应,但是至少要在找不到user情况下将错误发送回客户端,例如:

if (!user) {
  console.log('no user!');
  return res.status( 404 ).json({ message: 'User not found' });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM