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. 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 -X POST -d '{ "url": "http://localhost:8000/event"}' http://localhost:8000/subscribe/topic1
Data 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());
Solution 1:
You need to add this option to your CURL request:
-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