添加 bodyParser() 挂起所有 api 请求
Adding bodyParser() hangs all api requests
我需要通过在 api 代理期间添加一些东西来编辑请求的 body,我能想到的唯一方法是使用 body 解析器来获得访问权限至 req.body
.
const compression = require('compression');
const express = require('express');
const request = require('request');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
// Add body parser
app.use(bodyParser.json());
// Enable gZip compression
app.use(compression());
// Disable X-Powered-By header for security reasons
app.disable('x-powered-by');
// Add cookie parser
app.use(cookieParser());
// Example proxy
app.post('/api', (req, res) => {
const url = 'https://my.api.com';
req.pipe(request({
url,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
auth: {
user: 'user',
pass: 'password'
}
})).pipe(res);
});
然而,一旦我添加 body 解析器 api 挂起,它就会挂起,然后超时。请注意,我还没有在示例中添加任何 body 操作,因为我需要先解决这个 api 挂起问题。
您可以将 compression 中间件移到 bodyParser 之前,并在 bodyParser.json
之前再添加一个 bodyParser.urlencoded
作为下面解析 application/x-www-form-urlencoded
// Enable gZip compression
app.use(compression());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
// Add body parser
app.use(bodyParser.json());
我需要通过在 api 代理期间添加一些东西来编辑请求的 body,我能想到的唯一方法是使用 body 解析器来获得访问权限至 req.body
.
const compression = require('compression');
const express = require('express');
const request = require('request');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
// Add body parser
app.use(bodyParser.json());
// Enable gZip compression
app.use(compression());
// Disable X-Powered-By header for security reasons
app.disable('x-powered-by');
// Add cookie parser
app.use(cookieParser());
// Example proxy
app.post('/api', (req, res) => {
const url = 'https://my.api.com';
req.pipe(request({
url,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
auth: {
user: 'user',
pass: 'password'
}
})).pipe(res);
});
然而,一旦我添加 body 解析器 api 挂起,它就会挂起,然后超时。请注意,我还没有在示例中添加任何 body 操作,因为我需要先解决这个 api 挂起问题。
您可以将 compression 中间件移到 bodyParser 之前,并在 bodyParser.json
之前再添加一个 bodyParser.urlencoded
作为下面解析 application/x-www-form-urlencoded
// Enable gZip compression
app.use(compression());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
// Add body parser
app.use(bodyParser.json());