【发布时间】: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>
【问题讨论】:
-
如果可能的话,我强烈推荐使用
fetchAPI,我发现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