Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

body must be type object #1046

Closed
nathan-rogers opened this issue Aug 1, 2024 · 4 comments
Closed

body must be type object #1046

nathan-rogers opened this issue Aug 1, 2024 · 4 comments
Labels
bug Something isn't working help wanted Extra attention is needed

Comments

@nathan-rogers
Copy link

nathan-rogers commented Aug 1, 2024

💬 body must be type object

I have a very simple POST end point, which is invalidating the most bare-bones request so that I don't even know how to troubleshoot further. I have a barebones fastify instance with only 1 other end point, running on the same local machine as a browser application trying to make a POST request via the fetch API bundled with my browser, which is up-to-date Chrome.

Fastify Schema

{
  handler: (req, res) => res.send({status: 200, msg:'success'}),
  schema: {
    description: 'submit a filled form',
    body: { 
      type: 'object', 
      required: ['name'],
      properties: { 
        value: {type:'object'}, 
        name:  {type:'string'}
    }}
  }
}

Client JS

    const result = await fetch(url, {
      method:'POST',
      mode:'no-cors', // because I'm running locally atm
      body: JSON.stringify({
        name: 'bob',
        value: {}
      })
    }).then(data => data.text())
      .then(text => console.log(text))
      .catch(err => console.log(err))

Fastify Output

{
  "level": 30,
  "time": 1722528339845,
  "pid": 246204,
  "hostname": "ITDEVNB-01",
  "reqId": "req-1",
  "res": {
    "statusCode": 400
  },
  "err": {
    "type": "Error",
    "message": "body must be object",
    "stack": "Error: body must be object\n    at defaultSchemaErrorFormatter (/home/n/apps/api/node_modules/fastify/lib/context.js:114:10)\n    at wrapValidationError (/home/n/apps/api/node_modules/fastify/lib/validation.js:228:17)\n    at validate (/home/n/apps/api/node_modules/fastify/lib/validation.js:146:16)\n    at preValidationCallback (/home/n/apps/api/node_modules/fastify/lib/handleRequest.js:91:25)\n    at handler (/home/n/appsapi/node_modules/fastify/lib/handleRequest.js:75:7)\n    at /home/n/apps/api/node_modules/fastify/lib/contentTypeParser.js:199:9\n    at AsyncResource.runInAsyncScope (node:async_hooks:206:9)\n    at done (/home/n/apps/api/node_modules/fastify/lib/contentTypeParser.js:192:14)\n    at Parser.defaultPlainTextParser [as fn] (/home/n/apps/api/node_modules/fastify/lib/contentTypeParser.js:309:3)\n    at IncomingMessage.onEnd (/home/n/apps/api/node_modules/fastify/lib/contentTypeParser.js:283:27)",
    "statusCode": 400,
    "code": "FST_ERR_VALIDATION",
    "validation": [
      {
        "instancePath": "",
        "schemaPath": "#/type",
        "keyword": "type",
        "params": {
          "type": "object"
        },
        "message": "must be object"
      }
    ],
    "validationContext": "body"
  },
  "msg": "body must be object"
}

Your Environment

  • node version: v20.11.1
  • fastify version: ^4.26.2
  • os: Ubuntu 22.04.4 LTS
  • browser: Chrome (up to date)
@nathan-rogers nathan-rogers added the help wanted Extra attention is needed label Aug 1, 2024
@dosubot dosubot bot added the bug Something isn't working label Aug 1, 2024
@nathan-rogers
Copy link
Author

I have tried just about every obvious thing you could think of.

  • with and without JSON.stringify
  • with and without Content-Type and Accepts and origin in the request headers
  • setting consumes to ['application/json'] on the schema side

I'm really struggling for what to try next. The type of the thing I'm sending as the body is definitely an object...

@Eomm
Copy link
Member

Eomm commented Aug 2, 2024

Could you add a Minimal, Reproducible Example?

Without it, we are unable to help you.

@nathan-rogers
Copy link
Author

nathan-rogers commented Aug 2, 2024

Minimally Reproducable Example

Fresh installation of fastify. This is the index.js with node version: v20.11.1

const fastify = require('fastify')()

const schema = {
  handler: (req,res) => res.send({msg: 'zomg'}),
  schema: {
    body: { 
      type: 'object', 
      required: ['name'],
      properties: { 
        value: {type:'object'}, 
        name:  {type:'string'}
    }}
  }
}

fastify.register((fast, opts, done) => {
  fast.post('/rofl', schema)
  done()
})


const start = async () => {
  try       { await fastify.listen({port: 1337, host:'0.0.0.0'}) } 
  catch (e) { fastify.log.error(e);process.exit(1) } 
}

start()

Now open a chrome browser console and paste in the following

  const submit = async (event) => {
    const url = 'http://localhost:1337/rofl'
    const json = await fetch(url, {
      method:'POST',
      mode:'no-cors',
      body: JSON.stringify({
        name: 'bob',
        value: {}
      })
    }).then(data => data.text())
      .then(text => console.log(text))
      .catch(err => console.log(err))
  }
  submit()

image

producing the following server log

{
  "level": 30,
  "time": 1722607306150,
  "pid": 252188,
  "hostname": "ITDEVNB-01",
  "reqId": "req-1",
  "res": {
    "statusCode": 400
  },
  "err": {
    "type": "Error",
    "message": "body must be object",
    "stack": "Error: body must be object\n    at defaultSchemaErrorFormatter (/home/n/apps/repro/node_modules/fastify/lib/context.js:114:10)\n    at wrapValidationError (/home/n/apps/repro/node_modules/fastify/lib/validation.js:228:17)\n    at validate (/home/n/apps/repro/node_modules/fastify/lib/validation.js:146:16)\n    at preValidationCallback (/home/n/apps/repro/node_modules/fastify/lib/handleRequest.js:92:25)\n    at handler (/home/n/apps/repro/node_modules/fastify/lib/handleRequest.js:76:7)\n    at /home/n/apps/repro/node_modules/fastify/lib/contentTypeParser.js:199:9\n    at AsyncResource.runInAsyncScope (node:async_hooks:206:9)\n    at done (/home/n/apps/repro/node_modules/fastify/lib/contentTypeParser.js:192:14)\n    at Parser.defaultPlainTextParser [as fn] (/home/n/apps/repro/node_modules/fastify/lib/contentTypeParser.js:309:3)\n    at IncomingMessage.onEnd (/home/n/apps/repro/node_modules/fastify/lib/contentTypeParser.js:283:27)",
    "statusCode": 400,
    "code": "FST_ERR_VALIDATION",
    "validation": [
      {
        "instancePath": "",
        "schemaPath": "#/type",
        "keyword": "type",
        "params": {
          "type": "object"
        },
        "message": "must be object"
      }
    ],
    "validationContext": "body"
  },
  "msg": "body must be object"
}

@Eomm
Copy link
Member

Eomm commented Aug 3, 2024

Now open a chrome browser console and paste in the following

It is a cors issue due to the no-cors mode:

In detail:

Content-Type needs to have a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain.

So, no application/json payload.

If you log it:

  fast.addHook('onRequest', async function hook (request, reply) {
    console.log({ headers: request.headers, url: request.url, method: request.method })
  })

You will see:

  headers: {
    host: 'localhost:1337',
    connection: 'keep-alive',
    'content-length': '25',
    'sec-ch-ua': '',
    'sec-ch-ua-platform': '"macOS"',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0',
    'content-type': 'text/plain;charset=UTF-8',
    accept: '*/*',
    origin: 'http://localhost',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-mode': 'no-cors',
    'sec-fetch-dest': 'empty',
    'accept-encoding': 'gzip, deflate, br, zstd',
    'accept-language': 'it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7'
  },

You need to fix your FE/BE cors setup.
I suggest to check this plugin: https://github.com/fastify/fastify-cors

@Eomm Eomm closed this as not planned Won't fix, can't repro, duplicate, stale Aug 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants