У меня есть строка req.session.userId = user._id;
в почтовом запросе с маршрутом /signin
.Когда я ставлю console.log(req.session.userId)
после этой строки, он возвращает идентификатор пользователя.Но req.session.userId возвращает неопределенное значение в почтовом запросе с маршрутом /notes
.Как я могу получить идентификатор пользователя?
сеанс в MongoDB Compass действительно содержит 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');
});