我一直在尝试找出此代码的问题,该代码在获得客户端登录授权后在服务器中设置cookie。目前,它将打印代表控制台的空对象到控制台。后端服务器验证了登录名后,便会设置如下cookie:
// UserController.js (server-side)
res.cookie('token', token )
.cookie('username', username)
.status(201)
.send(username)
然后返回到此函数,该函数将其重定向到新页面
/// Login.js (client-side)
const login = async () => {
var token = params.get("token")
const config = {
method: 'POST',
url: url + "/users/fbLogin",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:3000"
},
data: {
fb_id: fb_id,
token: token,
}
}
var res = await axios(config)
if(res.status === 201) {
window.location.assign(`${client_url}/home?user=${res.data}`);
}
}
页面重定向后,它会像下面这样将获取请求发送回服务器:
// UserHome.js
function validateUser(username){
// axios.defaults.withCredentials = true
const config = {
method: 'GET',
url: url + '/users/auth',
// withCredentials: 'true',
headers: {
"Content-Type": "application/json",
'Access-Control-Allow-Credentials': true,
"Access-Control-Allow-Origin": "http://localhost:3000"
},
data: {
username: username
},
}
try {
var res = axios(config)
} catch(err) {
console.log(err)
}
}
此请求由以下功能处理:
// UsersController.js
UsersController.auth = async function(req, res) {
console.log(req.cookies)
}
当前打印出的内容:[对象:null原型] {}
有人知道我在做什么错吗?我也在Chrome和Safari中对其进行了测试,并且存在相同的问题。
快速设置:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const cors = require('cors');
const api = require('./api/index.js');
const passport = require('passport')
const cookieParser = require("cookie-parser");
var cookieSession = require('cookie-session')
// setup the connection
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// use it before all route definitions
app.use(cors({origin: 'http://localhost:3000'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(cookieSession({
auth: 'session',
keys: 'secret',
maxAge: 900000,
httpOnly: false,
sameSite: false,
overwrite: true
}))
app.use(cookieParser());
app.use('/', api);
app.listen(port, () => console.log(`Listening on port ${port}`));