Richard Rublev
Richard Rublev

Reputation: 8164

How to POST Json with curl? SyntaxError: Unexpected token n in JSON at position 1

I have Node.js app. When I try to POST

curl -X POST -H "Content-Type: application/json" -d "{"name":"richard","email":"[email protected]" }" http://localhost:3000/collections/curl-test

I got error

<body>
<pre>SyntaxError: Unexpected token n in JSON at position 1<br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)<br> &nbsp; &nbsp;at parse (/home/miki/amardan/ch8/newrest/node_modules/body-parser/lib/types/json.js:89:19)

If I add -d -d

[1/2]: name:'richard' --> <stdout>
--_curl_--name:'richard'
curl: (3) URL using bad/illegal format or missing URL

[2/2]: email:'[email protected]' --> <stdout>
--_curl_--email:'[email protected]'
curl: (6) Could not resolve host: rublev.co'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>

Error

SyntaxError: Unexpected token - in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/home/miki/amardan/ch8/newrest/node_modules/body-parser/lib/types/json.js:158:10)
    at parse (/home/miki/amardan/ch8/newrest/node_modules/body-parser/lib/types/json.js:83:15)
    at /home/miki/amardan/ch8/newrest/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/home/miki/amardan/ch8/newrest/node_modules/raw-body/index.js:224:16)
    at done (/home/miki/amardan/ch8/newrest/node_modules/raw-body/index.js:213:7)

If I go for text/html then I got

[{"_id":"5e9bf713bcea0e49314ed4f7"}]

Localhost output

::ffff:127.0.0.1 - - [Sun, 19 Apr 2020 07:04:09 GMT] "POST /collections/curl-test HTTP/1.1" 200 36 "-" "curl/7.65.3"

I am on Ubuntu 18.04. I will add few lines from my index.js. This is where body-parser starts

const app = express()

app.use(bodyParser.json())

app.param('collectionName', (req, res, next, collectionName) => {
    req.collection = db.collection(collectionName)
    return next()
})

app.post('/collections/:collectionName', (req, res, next) => {
    // TODO: Validate req.body
    req.collection.insert(req.body, {}, (e, results) => {
      if (e) return next(e)
      res.send(results.ops)
    })
})

How to solve this issue?

Upvotes: 1

Views: 1472

Answers (1)

Richard Rublev
Richard Rublev

Reputation: 8164

This works

 curl -X POST -H "Content-Type: application/json" -d '{"name":"richard","email":"[email protected]"}' http://localhost:3000/collections/curl-test

Output

[{"name":"richard","email":"[email protected]","_id":"5e9c1818ea90fe2665db90ed"}]

Upvotes: 2

Related Questions