为什么cookieParser不返回值?

时间: 2024-05-10 admin IT培训

为什么cookieParser不返回值?

为什么cookieParser不返回值?

我在客户端使用vue,vue-router,在服务器端使用Express,morgan(MEVN应用)

因此,在客户端,我正在使用vue-cookies设置cookie

this.$cookies.set('Login', this.login, new Date(Date.now() + 86400 * 5 * 1000))
this.$cookies.set('Password', this.password, new Date(Date.now() + 86400 * 5 * 1000))

并且在服务器端,我正在使用cookieParser

所以,在app.js我有这样的代码

const express       = require('express');
const morgan        = require('morgan');
const cors          = require('cors');
const bodyParser    = require('body-parser');
const cookieParser  = require('cookie-parser');

const config        = require('./config/config');
const db            = require('./controllers/DB');
const mCLogs        = require('./modelControllers/Logs');
const mCLogin       = require('./modelControllers/Login');

const app = express();
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(cors());
app.use(cookieParser()); /*cookie parser*/

而且,在文件./modelControllers/Login中,我有这样的GET请求代码

    exports.checkLoginSession = async (req, res, next) => {
/*its not all of the code*/
        var loginHash = req.cookies['Login'];
        console.log(loginHash)
        if(loginHash == undefined) {
            res.send({
                logged: false,
                description: "err mes"
            });
        } else {
            res.send({
                logged: true,
                description: "mes"
            });
        }
    }

而且问题是,即使我有“登录” cookie,var loginHash = req.cookies['Login'];总是返回未定义的

添加:我如何称呼此方法:

客户端和使用axios

mounted () {
    this.getLoginData()
  },
  methods: {
    async getLoginData () {
      const response = await LoginHandler.checkUserLoginSession()
      if (response.data.logged === true) {
        this.$router.push('/')
      } else {
        this.errorMessage = response.data.description
      }
    }
}

LoginHandler.js(客户端)

从'@ / services / api'导入api

export default {
  checkUserLoginSession () {
    return api().get('/login')
  }
}

app.js中的服务器端/登录链接

app.get('/login', mCLogin.checkLoginSession);
app.post('/login', mCLogin.checkUserData);

添加:

当我将这种代码与axios API一起使用时,它不起作用:

从'@ / services / api'导入api

export default {
  checkUserLoginSession () {
    return api().get('/login')
  }
}

因此,当我调用checkUserLoginSession app.get('/ login')时返回未定义的cookie值,但是,如果我在浏览器(服务器端)localhost:3000 / login中打开链接,则会返回正确的值

添加:checkUserData

exports.checkUserData = async (req, res) => {
    try {
        let login = req.body.login;
        let password = req.body.password;

        const user = await db.users.findOne({
            where: {
                Login: login,
                Password: password
            }
        });
        if(user == null)
        {
            res.send({
                logged: false,
                description: "Пользователь не найден."
            });
            return;
        }
        if(user.dataValues.Login == login && user.dataValues.Password == password)
        {
            res.send({
                logged: true,
                description: "Авторизация произошла успешно. Сейчас Вас перенаправит!"
            });
            return;
        }
    }
    catch(ex) {
        res.send({
            logged: false,
            description: "Произошла ошибка на стороне сервера."
        });
        console.log(ex);
        return;
    }

}

如果我将withCredentials: true添加到axios.create,则服务器返回cookie值,但是我在控制台行出现此错误

Access to XMLHttpRequest at 'http://localhost:3000/login' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
回答如下:

您必须将cookie与服务器端的响应一起发送。在您的res.send之前。 (当凭据确定时)。

res.setHeader('Set-Cookie','test=value');
res.cookie('yourcookie', 'yes', { maxAge: 900000, httpOnly: false});

免责声明,在生产中使用httpOnly: true

之后,您应该在客户端看到cookie作为响应。 (“存储”标签浏览器)