簡體   English   中英

Express.JS中未提及Content-Type時如何處理CURL POST請求

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

我正在向我的 node.js 服務器發送以下 CURL 請求。 但是當我嘗試提取數據時,它以一種奇怪的格式顯示,我不知道如何解析。

CURL 請求:

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

數據 Output

{ '{ "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());

您需要將此選項添加到您的 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

@KunalGulati,你好布朗尼!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM