【问题标题】:nodejs get raw body from POST request [duplicate]nodejs从POST请求中获取原始正文[重复]
【发布时间】:2021-10-01 00:05:57
【问题描述】:

我在 tradingview 中有一个警报,它向我的服务器发送一个带有请求的 webhook,其中包含一些信息的普通正文。 webhook 发送 PLAIN TEXT,它不发送 JSON 数据。

我想知道是否有任何方法可以获取纯文本数据

这是 JSON 网络钩子

这就是我的代码

const express = require('express');

const app = express();

app.post('/webhook', (req, res) => {
    
})

app.listen(8080, () => {console.log("listening on port 8080")})

【问题讨论】:

  • json.loads?你在哪里定义了json
  • 劳伦斯,我在烧瓶 (python) 中使用该函数,然后我正在搜索该函数,但 IDK 它对我不起作用
  • 你说它不发送JSON,然后你显示一个JSON的截图。它发送 JSON 还是不发送?

标签: node.js express webhooks


【解决方案1】:

更新: body-parser 中间件已弃用。 @Aurast 提供的答案是使用 express 的中间件的正确方法。


您需要添加一个中间件来解析和提取 HTTP 请求的正文。

您可以安装body-parser 中间件:

$ npm install body-parser

然后按如下方式使用:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.text())


更多信息请看这里:http://expressjs.com/en/resources/middleware/body-parser.html

【讨论】:

  • 我看到了,但是 body-parse 已被弃用,所以它不起作用
  • 我也刚看到这个。在这种情况下,@Aurast 提供的答案将是添加中间件的正确方法。
【解决方案2】:

您需要使用正文解析中间件。

您的问题不清楚 webhook 是纯文本还是 JSON。如果是纯文本:

const express = require('express');

const app = express();

app.use(express.text());

app.post('/webhook', (req, res) => {
  console.log(req.body); // If the request has Content-Type text/plain, the body will be parsed as text.
})

app.listen(8080, () => {console.log("listening on port 8080")});

如果是 JSON:

const express = require('express');

const app = express();

app.use(express.json());

app.post('/webhook', (req, res) => {
  console.log(req.body); // If the request has Content-Type application/json, the body will be parsed as JSON.
})

app.listen(8080, () => {console.log("listening on port 8080")});

【讨论】:

    【解决方案3】:
    const express = require('express');
    const app = express();
    app.use(express.json({limit: '10mb'}));
    
    app.post('/webhook', (req, res) => {
        const { psw, message }  = req.body
    })
    
    app.listen(8080, () => {console.log("listening on port 8080")})
    

    这样您就可以在 post 请求中提取正文。

    【讨论】:

      猜你喜欢
      • 2018-03-11
      • 2018-06-07
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 2017-09-02
      • 1970-01-01
      相关资源
      最近更新 更多