req.cookies返回undefined但设置了cookie

时间:2017-10-04 14:05:36

标签: javascript express cookies

我在我的快递应用中使用cookie-parser。当请求根页面时,我使用res.cookie(name, value)在cookie上设置一个随机数,它设置正常(我在浏览器控制台上查看)。但是当我尝试记录req.cookie时,它总是返回undefined。

这是我的代码:

routes.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

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
});

4 个答案:

答案 0 :(得分:2)

您要查看将由快递设置的codepen

或者,如果您想使用存储在req.headers.cookie中的cookie-parse中间件的解析结果,那么您的问题就是您注册路由和中间件的顺序。

req.cookies

app.use('/', routes); app.use(express.static('public')); app.use(cookieParser()); 中的路由执行完毕后,cookie的解析完成。

您需要在要使用它的路线前移动routes

cookieParser()

答案 1 :(得分:1)

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

答案 2 :(得分:1)

当我从客户端(Angular)发送PUT请求而没有传递body对象时,这发生了。

我正在这样做(缺少第二个参数):

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

代替此:

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

答案 3 :(得分:0)

这解决了我的问题:

基本上,当您从客户端向服务器发送请求时,请确保添加withCredentials: true。例如

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