2

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/
mgibson
  • 6,103
  • 4
  • 34
  • 49
  • Possible duplicate of [How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?](https://stackoverflow.com/questions/7172784/how-to-post-json-data-with-curl-from-terminal-commandline-to-test-spring-rest) ā€“ M3talM0nk3y Sep 02 '17 at 01:36

1 Answers1

0

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/
ishegg
  • 9,685
  • 3
  • 16
  • 31
  • Thanks. On my Windows setup, the first suggestion doesn't work (I did try that) but the second does. Although it does require the outside quotes. ā€“ mgibson Sep 02 '17 at 08:56
  • Sorry, Iā€™m confused. Could you fix it? Yeah, the second one requires wrapping in double quotes **and** escaping the inside double quotes. ā€“ ishegg Sep 02 '17 at 11:47