npm express会话无法获取值或为空

nzk0hqpo  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(380)

我正在使用express会话保存路由器中的一些值,并在以后显示它们。但是,即使我在设置后立即将req.session.euro_金额记录到console.log中,它也会显示正确的金额。
routes/api/convert.js:

const express = require('express');
const router = express.Router();
const CC = require('currency-converter-lt')
router.post('/', (req, res) => {
    let amount_e = parseInt(req.body.amount_e);
    let amount_k = parseInt(req.body.amount_k
    let currencyConverter = new CC()

    if(!amount_e){
        // Convert to Euro
        currencyConverter.from("HRK").to("EUR").amount(amount_k).convert().then((response) => {
            console.log(response); // Correct value that I want to save
            req.session.euro_amount = response;
            console.log("Set amount in session: " + req.session.euro_amount); // Output: Set amount in session: 0.65
        })
    }
    res.redirect('/');

routes/index.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  let euro_amount = req.session.euro_amount;
  res.render('index', { title: 'Express', euro_amount });
});

module.exports = router;

app.js(简化):

var express = require('express');
var path = require('path');
var session = require('express-session');

var indexRouter = require('./routes/index');
var convertRouter = require('./routes/api/convert');

var app = express(); 

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');  

app.use(session({secret: 'S0meFancyS3c3t', resave: false, saveUninitialized: false, secure: false}));
app.use('/', indexRouter);
app.use('/api/convert', convertRouter);

module.exports = app;

js路由器正在工作,因为如果我手动覆盖欧元金额,它将被传输到前端而不会出现问题。
我在app.js中启动会话的方式是否有错误,或者我在这个设置中缺少的其他设置是否有错误?

smdnsysy

smdnsysy1#

在你的路由器里。post,u可能需要导入主体解析器,即后端需要('body-parser')才能使用req.body从前端获取u发布的数据。
如果没有主体解析器,req.body将无法获取您发布的数据。

相关问题