1
votes

I have received an error message stating: TypeError: bodyParser.json is not a function. My nuxt.config.js file has the following details regarding bodyparser (I originally had const bodyParser = require('body-parser') but an error appeared telling me that I had to use 'import' instead of 'require' so I changed it to 'import('body-parser'):

const bodyParser = import('body-parser')

export default {
  serverMiddleware: [
bodyParser.json(),
'~/api'
]
}

In my index.js file under the api folder, I have the following code:

const express = require('express')
const bodyParser = require('body-parser')

const router = express.Router()

const app = express()
router.use((req, res, next) => {
  Object.setPrototypeOf(req, app.request)
  Object.setPrototypeOf(res, app.response)
  req.res = res
  res.req = req
  next()

  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: true }))
})

router.post('/track-data', (req, res) => {
  console.log('Stored data!', req.body.data)
  res.status(200).json({ message: 'Success!' })
})

module.exports = {
  path: '/api',
  handler: router
}

Does anyone know how to get this to run? Everytime I enter 'npm run dev' in the terminal, I get the error 'TypeError: bodyParser.json is not a function'.

2

2 Answers

0
votes

I'm not familiar with nuxtjs specifically, but after looking at the nuxtjs module export docs it looks like your require inside your index.js should be a path to the file, rather than just the string body-parser which I have to imagine just gets processed something like an npm module if no path is supplied.

Additionally, at least in NodeJS and per the MDN docs on export and import, the syntax to import something that's exported with export default is import { destructuredModuleName } from 'string/representing/relative/or/absolute/path/to/module'

or

import * as whatYouWantToCallTheObject from 'string/representing/relative/or/absolute/path/to/module' would give you a more traditional module object with properties/methods matching properties on the exported module.

0
votes

I had a slightly similar issue and could solve it with this code, first i imported express in the config file, before i did it like you, with bodyParser, but got a deprecated warning, then i use it in the api folder, in the index file, like so:

// nuxt.config.js
import express from 'express';
export default {
  ssr: true,
  .......,
  .......,
  serverMiddleware: [
    express.json(),
    // Api middleware
    { path: '/api', handler: '~/api/index.js' },
  ]
} 

// ~/api/index.js
// Router setup for serverMiddleware
router.use((req, res, next) => {
  Object.setPrototypeOf(req, app.request);
  Object.setPrototypeOf(res, app.response);
  req.res = res;
  res.req = req;
  next();
});

export default {
  path: '/api',
  handler: router
};

hope it helps ! πŸ‘