1
  1. 如果放置在 cookie 解析器之前,中间件可以正常工作。但是会话变得未定义。
  2. 如果我在 cookie 解析器之后移动代理中间件,它不会代理请求静默失败而没有任何错误。我尝试创建一个发布请求,但没有任何反应。
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'));
    }      
}));
4

1 回答 1

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()
    }
  },

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

于 2021-08-02T08:04:08.883 回答