nuxt: Cannot read properties of undefined (reading 'content-type') using express js
Environment
- Operating System:
Linux - Node Version:
v16.10.0 - Nuxt Version:
3.0.0-27265876.3cd4494 - Package Manager:
yarn@1.22.17 - Bundler:
Vite - User Config:
serverMiddleware - Runtime Modules:
- - Build Modules:
-
Describe the bug
serverMiddleware doesn’t work with express.js (4.17.1) and throws “Cannot read properties of undefined (reading 'content-type')” error
Reproduction
Clone a repository with the bug and run it as dev server
$ git clone https://github.com/martiliones/nuxt-express-bug
$ cd nuxt-express-bug && yarn install
$ yarn dev
Open http://localhost:3000/projects/ in your browser
Additional context
I tested serverMiddleware with h3 and it works just fine:
// api/index.js
import { createApp } from 'h3'
const app = createApp()
app.use('/projects', () => JSON.stringify([
{
name: 'asdsad',
type: ['asdsad', 'asdsad']
}
]))
Logs
Cannot read properties of undefined (reading 'content-type')
at ServerResponse.getHeader (node:_http_outgoing:597:24)
at ServerResponse.res.get (./node_modules/express/lib/response.js:789:15)
at ServerResponse.json (./node_modules/express/lib/response.js:263:13)
at file://./.nuxt/nitro/index.mjs:139:7
at Layer.handle [as handle_request] (./node_modules/express/lib/router/layer.js:95:5)
at next (./node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (./node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (./node_modules/express/lib/router/layer.js:95:5)
at ./node_modules/express/lib/router/index.js:281:22
at Function.process_params (./node_modules/express/lib/router/index.js:335:12)
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 4
- Comments: 33 (13 by maintainers)
Using the full URL prevents Nitro from making a local call. So it’s a workaround with a performance cost.
Using the direct full URL eg
http://localhost:3000/api/whatever
Instead of
api/whatever
Worked for me …
I ended up writing my own router based on h3 that can handle different request methods and route parameters. It’s probably not the best approach, but if anyone wants to use it here it is: router.ts
So is this a bug then? Using the full url works for me but would love to have the url relative
The problem only seems to exist when the API is used while SSR. Requesting with postman does not throw any errors.
Not sure if that’s the case 🤔 cc @danielroe
If you want to debug it, the issue is that
expresssets the prototype ofreq/resto be the native Node classes, rather than theunenv-provided classes we’re using in Nuxt. That means the internal object that Node uses to store headers is undefined and can’t be read from.