Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express - Adding a JSON payload with curl causing parsing error

Code:

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

app = express()
app.use(bodyParser.json());

app.post('/', function (req, res)
{
    res.send("Ok")
})

app.listen(7000)

Works:

curl -X POST localhost:7000/

Fails:

Cmd: curl -H "Content-Type: application/json" -d {"day":"Friday"} localhost:7000/

Error: SyntaxError: Unexpected token d in JSON at position 1

Any ideas?

Resolution:

The problems seems to be due to the fact I was doing this on Windows. The following commands worked.

curl -H "Content-Type: application/json" -d {"""day""":"""Friday"""}localhost:7000/

curl -H "Content-Type: application/json" -d {\"day\":\"Friday\"} localhost:7000/

curl -H "Content-Type: application/json" -d "{\"day\":\"Friday\"}" localhost:7000/
like image 217
mgibson Avatar asked Nov 27 '25 23:11

mgibson


1 Answers

The cURL command gets confused with the quotes (see how it thinks the first character is "d"?). You need to wrap the JSON data in single quotes:

curl -H "Content-Type: application/json" -d '{"day":"Friday"}' localhost:7000/

You can also escape the quotes:

curl -H "Content-Type: application/json" -d "{\"day\":\"Friday\"}" localhost:7000/
like image 141
ishegg Avatar answered Nov 29 '25 11:11

ishegg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!