Express-Sesison不保存路线

发布于 2025-01-21 20:57:37 字数 2397 浏览 3 评论 0原文

我有ExpressJS服务器,我想在会议上实现,但是它似乎并不能保存会话。

该流量是:

  1. post to/api/login
  2. 从/api/viewsession获取,

但是,session ['quote']返回undefined

我怀疑这可能是因为我试图从其他URL获取会话。因此,我将get方法添加到/api/login中,但它也返回了undefined

有人可以指向正确的方向吗?几个小时的谷歌搜索无济于事,我有点迷路了。

以下是我的index.js的代码和我的路由api.js

另外,我正在使用

  • NPM-版本8.3.1
  • 节点 - 版本v16.14.0
  • npm i cors - 版本2.8.5
  • npm i Express -Session - 版本1.17.2
  • npm i Express - 版本4.17.3

index.js

const express = require('express')
const formidable = require('express-formidable');
const cors = require('cors');
const session = require('express-session');

const api = require('./routes/api');

const app = express()
const port = 3000;

app.use(express.json());
app.use(formidable());
app.use(
    cors({
        origin: true,
        optionsSuccessStatus: 200,
        credentials: true,
    })
);
app.options(
    '*',
    cors({
        origin: true,
        optionsSuccessStatus: 200,
        credentials: true,
    })
);
app.use(
    session({
        saveUninitialized: false,
        secret: "anyrandomstring",
        cookie: { maxAge: 36000000 }
    })
);

//Routes
app.use('/api', api);

//Navigation
app.get('/', function (req, res) {
    res.render('index');
    res.send("Hi!");
})

//App Start
app.listen(port, () => {
    console.log(`App Listening on port ${port}`);
})

api.js api

"use strict";
const express = require("express");
let router = express.Router();

router
.route('/dump')
.post(async (req, res) => {
    console.log(req.fields);
    res.send({status: "ok"})
})

router
.route('/login')
.post(async (req, res) => {
    //Saving in Session
    req.session['stuff'] = "123456";

    res.send("Ok");
})

router
.route('/viewSession')
.get((req, res) => {
    console.log(req.session['stuff']);
    res.send("ok");
})

module.exports = router;

,这是我发送发布/获取请求的方式

$.ajax({
  url: "http://localhost:3000" + '/api/login',
  type: "POST",
  crossDomain: true,
  dataType: "json",
  data: {},
  success: function (response) {
     console.log(response);
  }
})

I have a ExpressJS server and I would like to implement in Sessions however it doesn't seem to save the sessions.

The flow is to:

  1. POST to /api/login
  2. GET from /api/viewSession

However, the session['stuff'] returns undefined.

I suspected it might be because i'm trying to GET the session from a different URL. So I added a GET method to /api/login but it returned undefined too.

Could somebody point me in the right direction please? I'm a little lost after a few hours of Googling to no avail.

Here below is my code for index.js and my route api.js.

Also, I'm using

  • NPM - Version 8.3.1
  • Node - Version v16.14.0
  • npm i cors - Version 2.8.5
  • npm i express-session - Version 1.17.2
  • npm i express - Version 4.17.3

index.js

const express = require('express')
const formidable = require('express-formidable');
const cors = require('cors');
const session = require('express-session');

const api = require('./routes/api');

const app = express()
const port = 3000;

app.use(express.json());
app.use(formidable());
app.use(
    cors({
        origin: true,
        optionsSuccessStatus: 200,
        credentials: true,
    })
);
app.options(
    '*',
    cors({
        origin: true,
        optionsSuccessStatus: 200,
        credentials: true,
    })
);
app.use(
    session({
        saveUninitialized: false,
        secret: "anyrandomstring",
        cookie: { maxAge: 36000000 }
    })
);

//Routes
app.use('/api', api);

//Navigation
app.get('/', function (req, res) {
    res.render('index');
    res.send("Hi!");
})

//App Start
app.listen(port, () => {
    console.log(`App Listening on port ${port}`);
})

api.js

"use strict";
const express = require("express");
let router = express.Router();

router
.route('/dump')
.post(async (req, res) => {
    console.log(req.fields);
    res.send({status: "ok"})
})

router
.route('/login')
.post(async (req, res) => {
    //Saving in Session
    req.session['stuff'] = "123456";

    res.send("Ok");
})

router
.route('/viewSession')
.get((req, res) => {
    console.log(req.session['stuff']);
    res.send("ok");
})

module.exports = router;

Also, this is the way I send the POST/GET request

$.ajax({
  url: "http://localhost:3000" + '/api/login',
  type: "POST",
  crossDomain: true,
  dataType: "json",
  data: {},
  success: function (response) {
     console.log(response);
  }
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小嗲 2025-01-28 20:57:37

如果您要使用xmlhttprequest进行跨域请求,并且要允许服务器处理请求的服务器设置cookie,则需要设置 withCredentials:true

使用jQuery:

$.ajax({
  url: "http://localhost:3000" + '/api/login',
  type: "POST",
  crossDomain: true,
  xhrFields: { withCredentials: true },
  dataType: "json",
  data: {},
  success: function (response) {
     console.log(response);
  }
})

If you're making cross-domain requests with XMLHttpRequest and you want to allow cookies to be set by the server handling the request, you need to set withCredentials : true.

Using jQuery:

$.ajax({
  url: "http://localhost:3000" + '/api/login',
  type: "POST",
  crossDomain: true,
  xhrFields: { withCredentials: true },
  dataType: "json",
  data: {},
  success: function (response) {
     console.log(response);
  }
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文