如果放置在cookieparser之后,http-proxy-middleware不会代理请求

时间:2017-04-03 18:47:23

标签: node.js express http-proxy-middleware

  
      
  1. 如果放在cookie解析器之前,中间件可以正常工作。但是   会话变得未定义。
  2.   
  3. 如果我在cookie解析器之后移动代理中间件则不会   代理请求静默失败,没有任何错误。我尝试创建一个帖子请求但没有任何反应。
  4.   
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var cors = require('cors');
var redis = require('redis');
var redisClient = redis.createClient();
var RedisStore = require('connect-redis')(session);
var proxy = require('http-proxy-middleware');
var config = require('config');

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

var app = express();

var sessionMiddleware = session({
  store: new RedisStore({
    client:redisClient
  }),
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(sessionMiddleware);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//cookie parser
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components',  express.static(__dirname + '/bower_components'));
app.use(cors());

//proxy middleware
app.use('/api', proxy({
    target: 'http://localhost:4000', 
    changeOrigin: true, 
    onProxyReq:  function (proxyReq, req, res) {
      proxyReq.setHeader('USER_ID', req.session.user_id);
      proxyReq.setHeader('TOKEN',config.get('token'));
    }      
}));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
  

http-proxy-middleware npm模块中间件

app.use('/api', proxy({
    target: 'http://localhost:4000', 
    changeOrigin: true, 
    onProxyReq:  function (proxyReq, req, res) {
      proxyReq.setHeader('USER_ID', req.session.user_id);
      proxyReq.setHeader('TOKEN',config.get('token'));
    }      
}));

1 个答案:

答案 0 :(得分:0)

如果您保留任何解析器中间件,它将格式化您的请求,这是 http-proxy-middleware 所不期望的。 我们应该将代理中间件放在解析器中间件之前,或者您可以尝试一下。

onProxyReq: function (proxyReq, req, res) {
    if (req.body) {
      const body = JSON.stringify(req.body)
      proxyReq.setHeader('Content-Type', 'application/json')
      proxyReq.setHeader('content-length', body.length)
      delete req.body
      proxyReq.write(body)
      proxyReq.end()
    }
  },

注意:必须对内容类型进行更改