[英]User not being authenticated, when trying to send a post request using react JS
I am following a video tutorial which shows how to authenticate a user using node and passport JS. 我正在观看一个视频教程,该视频教程显示了如何使用节点和通行证JS对用户进行身份验证。 This tutorial uses Hogan JS for as its view engine, however I want to follow the tutorial using React as my front end, everything works fine on the server side, if I test it with postman, ie, the user is authenticated, serialized, deserialized and the session gets stored, but as soon as I try it while accessing it from my react, The user does not get authenticated even though I am getting a correct user at the serialize function.
本教程使用Hogan JS作为其视图引擎,但是我想使用React作为我的前端,如果我使用邮递员对其进行测试(即用户已通过身份验证,序列化,反序列化),则一切在服务器端都可以正常运行并且存储了会话,但是当我从我的反应访问它时,只要尝试它,即使在序列化功能中找到了正确的用户,该用户也不会得到认证。
Here is my server file: 这是我的服务器文件:
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const bodyParser = require('body-parser');
require('./passport');
express()
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: false}))
.use(session({ secret: 'i love dogs', resave: false, saveUninitialized: false }))
.use(passport.initialize())
.use(passport.session())
.get('/', (req, res, next) => {
res.json({
session: req.session,
user: req.user,
authenticated: req.isAuthenticated()
});
})
.get('/login', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.json({name: 'login again'});
})
.post('/login', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
}, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}))
.listen(3001)
;
Here is my Passport file: 这是我的护照文件:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('./db');
const ObjectId = require('mongodb').ObjectId;
passport.use(new LocalStrategy(authenticate));
function authenticate (email, password, done) {
mongo.db.collection('users').find({email}).toArray((err, user) => {
if (err) return done(null, false, {message: err});
if (user.length === 0 || user[0].password !== password) {
return done(null, false, {message: 'Invalid user and password combination'});
}
done(null, user);
});
}
passport.serializeUser((user, done) => {
done(null, user[0]._id);
console.log(user);
});
passport.deserializeUser((id, done) => {
console.log(id);
mongo.db.collection('users').find({_id: ObjectId(id)}).toArray((err, user) => {
if (err) return done(null, false, {message: err});
done(null, user);
});
});
and here is the react login component: 这是react登录组件:
import React, {Component} from 'react';
export default class Login extends Component {
constructor (props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit (e) {
e.preventDefault();
const { username, password } = this.refs;
fetch(`http://localhost:3001/login?username=${username.value}&password=${password.value}`, {
method: 'post'
})
.then(blob => blob.json())
.then(res => {
console.log(res);
});
}
render () {
return (
<form onSubmit={this.onFormSubmit}>
<div>
<label>Email:</label>
<input type='text' ref='username' />
</div>
<div>
<label>Password:</label>
<input type='password' ref='password' />
</div>
<div>
<input type='submit' value='Log In' />
</div>
</form>
);
}
}
For the complete link of my project, here's the Github Link 对于我项目的完整链接,这是Github链接
Wow, I just figured out the answer,I just had to include: 哇,我只想出了答案,只需要包括:
credentials: 'include',
in the fetch method, and the set the headers to allow my server origin and set the allow credential headers to be true, here's how I did it: 在fetch方法中,将标头设置为允许我的服务器起源,并将allow凭据标头设置为true,这是我的操作方法:
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', true);
This took me a whole day to get to this solution. 我花了一整天的时间来解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.