【问题标题】:req.session.userId returns undefined in post requestreq.session.userId 在 post 请求中返回 undefined
【发布时间】:2018-11-14 20:14:32
【问题描述】:

我在带有路由/signin 的发布请求中有req.session.userId = user._id; 行。当我在该行后面加上console.log(req.session.userId) 时,它确实返回了用户 ID。但是 req.session.userId 在路由 /notes 的发布请求中返回未定义。如何获取用户 ID?

MongoDB Compass 中的会话确实包含 userId:

{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"userId":"5b1634522951cc240c2fe55f"}

客户发帖请求/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);
})

服务器发布请求/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');
});

【问题讨论】:

  • 你能显示邮政编码吗(客户端)。我猜你不包括“凭据”(cookies)。
  • 我尝试向客户端发布请求添加凭据:'include'。仍然返回未定义。它是怎么做的?

标签: node.js express session


【解决方案1】:

来自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)
})

您将需要 credentials 设置来处理您希望发送 cookie 的所有 fetch() 请求,无论它们是 GET 或 POST 还是任何其他动词。

【讨论】:

  • 我用同源或包含添加了这一行,但它仍然不起作用。我还能做什么?
  • @lmathl - 您正在执行此fetch() 的网页的 URL 是什么(在浏览器 URL 栏中)?
  • @lmathl - 那么,您显示代码的服务器是您的端口 8000 服务器,它与加载网页的端口 3000 服务器不同?为什么你认为 8000 端口的服务器和 3000 端口的服务器有相同的会话?您是否专门对两台服务器进行了编码以共享会话?
  • 我在我的服务器中使用了 app.use(session(...))。当我登录时,会创建 userId。所以必须有一个会话。
  • @lmathl - 我可以确认您在同一主机上使用两个单独的 node.js 服务器,一个位于网页来自的端口 3000,另一个位于您的端口 8000 '正在尝试使用fetch() 到达?为什么要使用两个单独的 node.js 服务器?当您登录并创建登录会话时,您在哪个服务器上执行此操作?
猜你喜欢
  • 2019-06-20
  • 1970-01-01
  • 2020-11-05
  • 2023-01-21
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多