mitchkman
mitchkman

Reputation: 6680

Posting string causes express body-parser to throw SyntaxError

I have the following simplified code:

'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())


const storage = {}

app.get('/', (req, res) => {
  res.send()
})

app.get('/ping', (req, res) => {
  res.send('pong')
})

;[
  'mycollection'
].forEach((collection) => {
  storage[collection] = []

  app.get(`/${collection}`, (req, res) => {
    console.log('GET /' + collection)
    return res.send(storage[collection])
  })
  app.post(`/${collection}`, (req, res) => {
    console.log('POST /' + collection)
    const item = req.body
    if (!item) return res.status(400).send({ message: 'Invalid body' })
    storage[collection].push(item)
    res.status(201).send({ message: 'Successfully added.' })
  })
})
const port = process.env.PORT || 3000
console.log('---> Running on port', port)
app.listen(port)

When I perform this request:

curl -X POST -H "Content-Type: application/json" -d '"test"' "http://localhost:3000/mycollection"

This gives me the following error:

SyntaxError: Unexpected token # in JSON at position 0

But "test" is valid JSON.

$ node
> JSON.parse('"test"')
> "test"

Upvotes: 2

Views: 1575

Answers (1)

mitchkman
mitchkman

Reputation: 6680

I solved it. From to the body-parser documentation:

https://github.com/expressjs/body-parser#strict

strict When set to true, will only accept arrays and objects; when false will accept anything JSON.parse accepts. Defaults to true.

So this fixed it:

app.use(bodyParser.json({
  strict: false
}))

Upvotes: 1

Related Questions