node.js - req.session.captcha 无法在 Node.js 中的不同端口上工作

标签 node.js

我正在尝试通过存储到 req.session 对象中来验证验证码。

express 服务器运行在 8181 上,客户端运行在 3000 上。但是在验证验证码中 req.session.captcha 未定义。请帮我。

我的服务器代码:

var captchapng = require('captchapng');
var express = require('express');
var app = express();
var session = require('express-session');
var cookieParser = require('cookie-parser');

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

app.use(cookieParser());
app.use(session({
    secret: 'abcd',
    resave: false,
    saveUninitialized: false,
    cookie: {maxAge: 1000*60*60*24*30}, //30 days
  }));



app.get('/captcha.png', function (request, response) {
    if(request.url == '/captcha.png') {
        var randNumber = Math.random()*9000+1000;
        var p = new captchapng(80,30,parseInt(randNumber)); // width,height,numeric captcha
        p.color(0, 0, 0, 0);  // First color: background (red, green, blue, alpha)
        p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)
        var no  = parseInt(randNumber);
        request.session.captcha = no.toString();
        console.log(parseInt(randNumber));
        console.log(request.session);
        var img = p.getBase64();
        var imgbase64 = new Buffer(img,'base64');
        response.writeHead(200, {
            'Content-Type': 'image/png'
        });
        response.end(imgbase64);
    } else response.end('');
})

app.get('/verify-captcha', (req, res) => {
    let captcha = req.query.captcha;
    console.log(captcha, req.session);
    if(req.session.captcha === Number(captcha)){
        res.send({message:'verified'})
    }
    else
        res.send({message: "Not Verified!"})
})

app.listen(8181);

我的客户代码:

索引.pug

extends layout

block content
  h1= title
  p Welcome to #{title}
  #image
    img(src="http://localhost:8181/captcha.png")
  #verify
    input(type="text" placeholder="Enter captcha to verify" id="captcha")
    button(type="button") Submit

验证码.js

$(document).ready(function(){
    $('button').click(function(e){
        var captcha = $('#captcha').val();
        alert(captcha)
        $.ajax({
            url: 'http://localhost:8181/verify-captcha?captcha='+captcha,
            type:'GET',
            success: function(data){
                alert(data)
            },
            error: function(err) {
                alert(err);
            }
        })
    })
})

最佳答案

看起来 app.use(cookieParser()); 是问题所在......

来自快速 session 文档:

Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req/res. Using cookie-parser may result in issues if the secret is not the same between this module and cookie-parser.

删除cookieParser或使用相同的 secret app.use(cookieParser('abcd'));

另外:

您的客户端代码有一个拼写错误:

url: 'http://localhost:8181/verify-captch?captcha='+captcha,

应该是

url: 'http://localhost:8181/verify-captcha?captcha='+captcha,

在服务器代码中,您将字符串与数字进行比较,应该如下所示:

app.get('/verify-captcha', (req, res) => {
    let captcha = req.query.captcha;
    console.log(captcha, req.session);
    if(req.session.captcha === captcha){ // removed Number() here
        res.send({message:'verified'})
    }
    else
        res.send({message: "Not Verified!"})
})

编辑:

看起来像 $.ajax 发送 cookie,您必须添加

xhrFields: {
  withCredentials: true
},

最终客户端代码:

$(document).ready(function(){
    $('button').click(function(e){
        var captcha = $('#captcha').val();
        alert(captcha)
        $.ajax({
            url: 'http://localhost:8181/verify-captcha?captcha='+captcha,
            type:'GET',
            xhrFields: {
              withCredentials: true
            },
            success: function(data){
                console.log(data)
            },
            error: function(err) {
                console.error(err);
            }
        })
    })
})

工作示例:https://stackblitz.com/edit/js-y6dzda (注意:需要服务器在 localhost:8181 上运行)

关于node.js - req.session.captcha 无法在 Node.js 中的不同端口上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52019427/

相关文章:

javascript - 引用错误: my var is not defined

node.js - 检查 Mongoose 中是否存在文档(Node.js)

javascript - 配置 Node.js 应用程序以仅在特定端点上启用 CORS

node.js - Socket.io 配置错误

html - 如何将 html <li> 传输或转换为 html <datalist>

javascript - 如何使用我的 Node js 程序中任何元素的值?

javascript - require 在使用 browserify 时返回空对象

javascript - node.js + MySQL & JSON-result - 回调问题 & 对客户端无响应

node.js - 如何使用 node.js 删除 s3 上的文件夹?

node.js - Yarn 无法正确构建本地包