我正在使用fetch发送一个post请求并将一个令牌保存到express api后端的session中。但是,即使我在fetch中将credentials
设置为include
,也不会在会话中保存令牌。有人可以为我找出问题吗?感谢。
将令牌发送到api服务器:
fetch('http://localhost:3000/api/users', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
accessToken: user.accessToken,
})
})
.then(res => res.json())
.then(json => {
console.log(json);
})
.catch(error => {
console.log(error);
});
服务器端:
app.use(morgan('dev'))
app.use(cors({credentials: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'ssshhhhh', resave: true, saveUninitialized: true}));
app.post('/api/users', function(req, res) {
if (!req.session.accessToken) {
req.session.accessToken = req.body.accessToken;
}
...
...
})
app.get('/api/users/token', function(req, res) {
console.log(req.session);
if (req.session.accessToken) {
return res.json({ accessToken: req.session.accessToken });
}
return res.json({ accessToken: null });
})
从会话中检索令牌:
fetch('http://localhost:3000/api/users/token', {
credentials: 'include'
})
.then(checkStatus)
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
})
.catch(err => {
console.error(err);
});
修改 这是来自请求的标题:
{ host: 'localhost:3000',
accept: '*/*',
'if-none-match': 'W/"4d-oW2yTGBOs6aaA4LAPgNxNQ"',
cookie: 'connect.sid=s%3AHXDL6Az0hRZeSGsJgjhw4kvVONBLz-yn.sOOAqbxaLQ6Z%2FfCdfGOmXf9XsYl3JdHvP%2FmfkUln1xA',
'user-agent': 'cairn/1 CFNetwork/758.2.8 Darwin/15.3.0',
'accept-language': 'en-us',
'accept-encoding': 'gzip, deflate',
connection: 'keep-alive' }
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: false } }
GET /api/users/token 304 23.780 ms - -
{ host: 'localhost:3000',
'content-type': 'application/json',
cookie: 'connect.sid=s%3A1jat379BSZQCKvJV1pKL4_Cub9ApMFVI.m%2BQHkIewMl9Uzjg315GTC5aD5qpWESiQVNDnXrFFSbQ',
connection: 'keep-alive',
'if-none-match': 'W/"270-toaMUba3dhoaPENGp5EGaA"',
accept: 'application/json',
'accept-language': 'en-us',
'content-length': '484',
'accept-encoding': 'gzip, deflate',
'user-agent': 'cairn/1 CFNetwork/758.2.8 Darwin/15.3.0' }