【问题标题】:How to process CURL POST request in Express.JS when Content-Type is not mentioned未提及 Content-Type 时如何在 Express.JS 中处理 CURL POST 请求
【发布时间】:2021-01-07 08:22:47
【问题描述】:

我正在向我的 node.js 服务器发送以下 CURL 请求。但是当我尝试提取数据时,它以一种奇怪的格式显示,我不知道如何解析。

CURL 请求:

curl -X POST -d '{ "url": "http://localhost:8000/event"}' http://localhost:8000/subscribe/topic1

数据输出

{ '{ "url": "http://localhost:8000/event"}': '' }

处理请求的代码

app.post('/subscribe/:topic', (req, res) => {
    const topic = req.params.topic;

    /** Prnts a weird format of data !!! */
    console.log(req.body)
    
    let url = req.body.url;
    if (subscribeMap.has(topic)) { subscribeMap.get(topic).push(url) } else { subscribeMap.set(topic, [url]); }

    res.send(true)
})

我的快递服务器正在使用这样的正文解析器:

const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

【问题讨论】:

  • 能否提供数据输出?
  • @TasosBu 嘿,我的错,我忘了添加数据输出。输出是这样的 "{ '{ "url": "localhost:8000/event"}': '' }"

标签: javascript node.js express curl post


【解决方案1】:

您需要将此选项添加到您的 CURL 请求中:

-H "Content-Type: application/json"

像这样使用它:

curl -X POST -d '{"url": "http://localhost:8000/event"}' -H "Content-Type: application/json" http://localhost:8000/subscribe/topic1

【讨论】:

  • 哦,我看到了问题。但我不是发送 CURL 请求的人。当用户没有在他们的 CURL 请求中指定 Content-Type 时,我可以将其作为 JSON 处理吗
  • @KunalGulati 您可以使用helmet 强制执行此类标头。另一种选择是 JSON.parse() 正文的文本,但我建议您告诉发送 curl 请求的人使用此标头!
猜你喜欢
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 2020-09-30
相关资源
最近更新 更多