Home > Enterprise >  Node.js REST webservice with wrong Content-Type
Node.js REST webservice with wrong Content-Type

Time:07-27

I'm developing a REST webservice in Node.js, with fastify framework, designed to respond to a specific client.

This is how the client calls my webservice:

POST /myws/scan HTTP/1.1
Host: myhost.io
User-Agent: AGENT
Content-Length: 45
Accept: */*
Content-Type: application/x-www-form-urlencoded
X-Forwarded-For: xxx.xxx.xxx.xxx
X-Forwarded-Proto: http
Accept-Encoding: gzip

{"FIELD1":"testvalue","FIELD2":True,"FIELD3":90}

As you can see the Content-Type is "application/x-www-form-urlencoded" but the request payload is in "application/json" format. I can't change the client, so I have to adapt my webservice to manage this kind of calls. I tried with @fastify/formbody package but I receive an error because I think it expects the request body in "application/x-www-form-urlencoded" format.

I tried also with this code:

app.addContentTypeParser('application/x-www-form-urlencoded', function (req, body, done) {
    try {
      var json = JSON.parse(body)
      done(null, json)
    } catch (err) {
      err.statusCode = 400
      done(err, undefined)
    }
  })

but I have a JSON deserializing error. How I can manage these kind of calls and which is the best way to do that?

CodePudding user response:

body is a stream.

You need to add the parseAs option:

fastify.addContentTypeParser(
  'application/x-www-form-urlencoded',
  { parseAs: 'string' },
  function (req, body, done) {
    try {
      const json = JSON.parse(body)
      done(null, json)
    } catch (err) {
      err.statusCode = 400
      done(err, undefined)
    }
  }
)

I would check the first char before running the JSON.parse and I would use https://www.npmjs.com/package/secure-json-parse (as Fastify does under the hood)

  • Related