如何在node.js中覆盖或忽略内容类型请求标头

问题描述 投票:0回答:1

我有一个node.js服务器,正在使用application/json的内容类型调用它,但是它发送的正文不是json,而是以下形式的原始文本:

client_id=q9r71WPJtK5JWbkq7LAATEhQoXHQCJ9z&code_verifier=CiC6e0mZirQAwKkLvhiitiVuEvf2ZaFD7hsENkAhxyO&grant_type=authorization_code&code=TkdVtUfvtb4vKyJTRa9Z5F5G6_R8cwj6eIR6VGd0Tt0XX&redirect_uri=https%3A%2F%2Fuat.test.com.au

我一直在邮递员中进行通话,如果我将其设置为 application/json 它会显示

{}

如果我将其设置为text/plain,它会显示发送时的正确数据。

我正在模拟外部供应商系统,短期内无法更改内容类型。

问题:

是否有强制节点假设这是文本而不是 json 并进行处理的方法。

const express = require('express');
const app = express();
const PORT = 3000;
 
// Without this middleware
app.use(express.text());
app.post('/oauth/token', function (req, res) {
    console.log(req.body);
    res.end();
})
 
app.listen(PORT, function (err) {
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
});

邮递员的卷曲示例

curl --location 'http://127.0.0.1:3000/oauth/token' \
--header 'content-type: application/json' \
--data 'client_id=q9r71WPJtK5JWbkq7LAATEhQoXHQCJ9z&code_verifier=CiC6e0mZirQAwKkLvhiitiVuEvf2ZaFD7hsENkAhxyO&grant_type=authorization_code&code=TkdVtUfvtb4vKyJTRa9Z5F5G6_R8cwj6eIR6VGd0Tt0XX&redirect_uri=https%3A%2F%2Fuat.tab.com.au'

我一直在尝试的主要事情是研究忽略或覆盖请求标头中的内容类型的方法

node.js content-type
1个回答
0
投票

您可以添加

application/json
来确定中间件将解析什么媒体类型(默认情况下,如果内容类型为文本/纯文本,它只会解析请求正文)
text

这可能不是“最佳实践”,但会在你的情况下发挥作用

© www.soinside.com 2019 - 2024. All rights reserved.