问题
I have the line req.session.userId = user._id;
in a post request with route /signin
. When I put console.log(req.session.userId)
after that line, it does return the user id. But req.session.userId returns undefined in a post request with route /notes
. How can I get the user id?
session in MongoDB Compass indeed contains the userId:
{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"userId":"5b1634522951cc240c2fe55f"}
client post request /notes
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);
})
server post request /notes
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');
});
回答1:
From the MDN page for fetch():
By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).
And, without cookies, your server won't have access to session data.
The credentials option for fetch()
can have three main values: omit
, same-origin
, or include
. You will want to set one of the last two values like this:
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)
})
You will need the credentials
setting for ALL fetch()
requests that you want cookies sent with, whether they are GET or POST or any other verb.
来源:https://stackoverflow.com/questions/50698444/req-session-userid-returns-undefined-in-post-request