简体   繁体   English

req.cookies 返回未定义但 cookies 已设置

[英]req.cookies returns undefined but cookies are set

I am using cookie-parser in my express app.我在我的 express 应用程序中使用cookie-parser When the root page is requested I set a random number on the cookie using res.cookie(name, value) and it sets it fine (I checked on my browser console).当请求根页面时,我使用res.cookie(name, value)在 cookie 上设置了一个随机数,它设置得很好(我在浏览器控制台上检查过)。 But when I try to log req.cookie it always returns undefined.但是当我尝试记录req.cookie时,它总是返回 undefined。

Here's my code:这是我的代码:

routes.js路由.js

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

var movieTrailer = require('movie-trailer');

var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');

//Setup x-ray for scraping
var Xray = require('x-ray');
var x = Xray();

var debug = false;

router.get('/', (req, res) => {
  console.log('Page requested!');
  console.log('Cookies: ', req.headers.cookies); // For some reason this returns undefined

  var scrapeMovies = function(){
    return new Promise((resolve, reject) =>{
      fs.readFile('moviesRT.json', (err,data) =>{
        var movies = JSON.parse(data);
        resolve(movies);
      });
    });
  };

scrapeMovies().then(
    movies => {
      var randomInt = Math.floor(Math.random() * movies.length);
      res.cookie('randomInt', randomInt);
      var randomMovie = movies[randomInt];
      movieTrailer(randomMovie.title, (err, url) =>{
        console.log('Requesting trailer: ', randomMovie.title);
        if(err) throw err;
        var embedUrl = url.replace('watch?v=','embed/');
        console.log('Video ID: ', url.slice(32,url.length));
        randomMovie.trailerURL = embedUrl; //Add the embed URL to the randomMovie object before rendering it
        res.render('main',randomMovie,
        (err, html) =>
        {
          if(err) throw err;
          console.log('Rendering...');
          res.send(html);
          console.log("Done!");
        });
      });
    });

});

module.exports = router;

app.js应用程序.js

const express = require('express');

//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;

var routes = require('./routes');

var debug = true;

app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());

//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.listen(port, function () {
  console.log(`Server Starts on ${port}`);
  if(!debug) logs.disable(); //Disable logging if debug variable is false
});

You either want to check req.headers.cookie which will be set by express.您要么想检查由 express 设置的req.headers.cookie

Or if you want to use the the parsed result of the cookie-parse middleware that is stored in req.cookies then your problem is the order in which you register your routes and the middleware.或者,如果您想使用存储在req.cookies中的cookie-parse中间件的解析结果,那么您的问题是您注册路由和中间件的顺序。

app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());

The parsing of the cookie is done after the routes in routes have ben executed. cookie 的解析是在路由中的routes执行完成后完成的。

You need to move the cookieParser() before the route where you want to use it.您需要将cookieParser()移动到要使用它的路由之前。

app.use(cookieParser());
app.use('/', routes);
app.use(express.static('public'));

This solved my problem:这解决了我的问题:

Basically when you are sending a request to the server from client-side, make sure you add withCredentials: true .基本上,当您从客户端向服务器发送请求时,请确保添加withCredentials: true For example例如

{
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
    'withCredentials':true
  };

您需要将 cookie 读取为req.cookies['cookie-name']并将 cookie 设置为resInit.cookie('cookie-name', 'cookie-value')

This happened to me, when I sent a PUT request from the client-side (Angular) without passing the body object.这发生在我身上,当我从客户端(Angular)发送PUT请求而不传递body对象时。

I was doing this (second argument missing):我正在这样做(缺少第二个参数):

requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}

instead of this:而不是这个:

requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}

This worked for me这对我有用

in the frontend add credentials: 'include' as an option to your fetch API在前端添加credentials: 'include'作为您获取 API 的选项

A more elaborated code below for a get request下面是获取请求的更详细的代码

fetch('url', {credentials: 'include'})
.then(res => res.json())
.then(data => //do something with the data)
.catch(err => console.log(err.message));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM