express получение запроса любого типа
Чтобы получить запрос с body: <json>, нужно использовать .use(express.json())
Для текста аналогично .use(express.text())
Для xml уже нужно подключать библиотеку express-xml-bodyparser, .use(xmlparser())
Можно ли как-то без указаний .use(<>) принимать любые типы боди?
createProxyServer() {
const logger = new ConsoleLoggerService('proxy-server');
const proxy = httpProxy.createProxyServer({ changeOrigin: true });
const app = express();
app.all('*', (req, res, next) => {
logger.log(`Got request to ${req.path}, method=${req.method} `);
next();
});
registerServiceController(app);
app.all('*', async (req, res, next) => {
const { path } = req;
const proxyPath = findProxyPath(path);
const proxyHost = proxyMap[proxyPath];
if (proxyHost) {
logger.log(`Path [${path}] will be proxying to [${proxyHost}] host`);
proxy.web(req, res, {
target: {
protocol: 'https:',
host: proxyHost,
port: 443,
},
});
} else {
logger.error(`Proxy mapping for [${path}] not found, request not proxied`);
}
next();
})
.use(express.json())
.use(express.text())
.use(express.raw({ type: 'application/pdf', limit: '10mb' }))
.use(xmlparser())
.all('*', async (req, res, next) => {
const { path } = req;
const proxyPath = findProxyPath(path);
const proxyHost = proxyMap[proxyPath];
await ProxyStorageService.saveRequest(req, proxyHost);
});
app.listen(PORT);
logger.log(`Server is listening on port ${PORT}`);
}
Ответы (1 шт):
Автор решения: Eugene X
→ Ссылка
Можно ли как-то без указаний .use(<>) принимать любые типы боди?
Естественно... bodyParser.json() и им подобные просто возвращают обычный экспрессовский handlerFunction(req, res, next) который можно обернуть как тебе захочеться.
index.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const parsers = {
json: bodyParser.json(),
urlencoded: bodyParser.urlencoded({extended: false}),
}
app.use((req, res, next) => {
if ('POST' !== req.method) {
return next();
}
const contentType = String(req.get('Content-Type') || null);
switch (true) {
case contentType.indexOf('application/json') !== -1:
parsers.json(req, res, next);
break;
case contentType.indexOf('application/x-www-form-urlencoded') !== -1:
parsers.urlencoded(req, res, next);
break;
default:
res.status(422).send("422 Unprocessable Entity");
}
});
app.all("/endpoint", (req, res) => {
res.json(req.body);
});
app.listen(8000);
test-index.http
### Post json
POST http://localhost:8000/endpoint
Content-Type: application/json
Content-Length: 18
{"hello": "world"}
### POST urlencoded
POST http://localhost:8000/endpoint
Content-Type: application/x-www-form-urlencoded
Content-Length: 20
hello=world&test=123
### POST another
POST http://localhost:8000/endpoint
Content-Type: uncnown/type
Content-Length: 15
This is an test