简体   繁体   English

Express.JS中未提及Content-Type时如何处理CURL POST请求

[英]How to process CURL POST request in Express.JS when Content-Type is not mentioned

I am sending the following CURL request to my node.js server.我正在向我的 node.js 服务器发送以下 CURL 请求。 But when I try to extract the data, it shows it in a weird format, which I don't know how to parse.但是当我尝试提取数据时,它以一种奇怪的格式显示,我不知道如何解析。

CURL Request: CURL 请求:

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

Data Output数据 Output

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

Code to Process the Request处理请求的代码

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)
})

And my express server is using body parsers like this:我的快递服务器正在使用这样的正文解析器:

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());

You need to add this option to your CURL request:您需要将此选项添加到您的 CURL 请求中:

-H "Content-Type: application/json"

Use it like this:像这样使用它:

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

@KunalGulati,你好布朗尼!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM