[英]req.session.userId returns undefined in post request
我有一行req.session.userId = user._id;
在帶有route /signin
的發布請求中。 當我將console.log(req.session.userId)
放在該行之后時,它確實返回了用戶ID。 但是req.session.userId在帶有route /notes
的發布請求中返回undefined。 如何獲取用戶ID?
MongoDB Compass中的session確實包含userId:
{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"userId":"5b1634522951cc240c2fe55f"}
客戶帖子請求/注釋
fetch('http://localhost:8000/notes', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newNote)
})
.then(response => response.json())
.then(data => {
newNote._id = data._id;
const storedNotes = this.state.notes;
storedNotes.unshift(newNote);
this.setState({notes: storedNotes});
})
.catch(error => {
this.setState({error: 'Error adding note.'});
console.error('Error during adding note', error);
})
服務器發布請求/注釋
app.post('/notes', (req, res) => {
if(!req.body.content) {
return res.status(400).send({
message: "Note content can not be empty"
});
}
console.log(req.session.userId);
const note = new Note({
title: req.body.title || "Untitled Note",
content: req.body.content,
});
note.save()
.then(data => res.send(data))
.catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the Note."
});
});
};
server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/trial')
.then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...');
process.exit();
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
secret: 'work hard',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
app.use((req, res, next)=>{
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
if (req.method === "OPTIONS")
res.sendStatus(200);
else
next();
});
require('./routes/userRoutes')(app);
require('./routes/quoteRoutes')(app);
require('./routes/noteRoutes')(app);
app.listen(8000, function () {
console.log('Express app listening on port 8000');
});
默認情況下,如果站點依賴於維護用戶會話,則抓取將不會從服務器發送或接收任何cookie,從而導致未經身份驗證的請求(要發送cookie,必須設置憑據初始化選項)。
而且,如果沒有Cookie,您的服務器將無權訪問會話數據。
fetch()
的憑據選項可以具有三個主要值: omit
, same-origin
或include
。 您將需要像這樣設置最后兩個值之一:
fetch('http://localhost:8000/notes', {
method: 'POST',
credentials: 'include', // make sure session cookies are included
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newNote)
})
您需要與cookie一起發送的所有fetch()
請求的credentials
設置,無論它們是GET還是POST或任何其他動詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.