req.session.userId在post请求中返回undefined

时间:2018-06-05 11:00:38

标签: node.js express session

我在路由req.session.userId = user._id;的帖子请求中有/signin行。当我在该行之后放置console.log(req.session.userId)时,它会返回用户ID。但是req.session.userId在路由/notes的发布请求中返回undefined。我如何获得用户ID?

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');
});

1 个答案:

答案 0 :(得分:0)

来自MDN page for fetch()

  

默认情况下,fetch不会从服务器发送或接收任何Cookie,   如果站点依赖,则会导致未经身份验证的请求   维护用户会话(发送cookie,凭证init   必须设置选项)。

而且,如果没有cookie,您的服务器将无法访问会话数据。

fetch()的凭据选项可以包含三个主要值:omitsame-origininclude。您需要设置最后两个值中的一个,如下所示:

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的所有credentials请求,您需要fetch()设置,无论是GET还是POST或任何其他动词。