【问题标题】:XHR failed loading: POST on AJAX request (in React)XHR 加载失败:AJAX 请求上的 POST(在 React 中)
【发布时间】:2018-01-03 17:08:42
【问题描述】:

我认为 React 与此无关,但以防万一,这就是我正在处理的工作。我在向 /login 提交 AJAX 请求时收到错误 XHR failed loading: POST。我正在尝试使用 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);
    }
  }
}

编辑这是路线:

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);
});

编辑这是表格:

<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>

【问题讨论】:

  • 如果可能的话,我强烈推荐使用fetch API,我发现XMLHTTPRequest 接口让我很困惑。 fetch 使用起来要简单得多。如果fetch还有同样的问题,我可以帮忙调试。
  • @Sidney 我原本打算使用 fetch 但后来意识到它根本没有在 IE 中实现?
  • Here's a fetch polyfill 这样你就可以在IE中使用fetch了。
  • 那是什么错误,你看网络请求了吗?
  • I was originally going to use fetch but then realized it's not implemented at all in IE? ...箭头函数都不是,但你正在使用它们

标签: javascript ajax reactjs xmlhttprequest passport.js


【解决方案1】:

在您的代码中:

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

您没有向 UI 发送任何响应。不确定next(err) 如何处理响应,但至少在找不到user 的情况下,您想将一些错误发送回客户端,例如:

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

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 2016-11-17
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2014-06-29
    • 2015-01-28
    • 1970-01-01
    相关资源
    最近更新 更多