Why does Nuxt call the server for so many times on a single route/ page?
Below is the example I tested from their express-template:
import express from 'express'
import { Nuxt, Builder } from 'nuxt'
import api from './api'
const app = express()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000
app.set('port', port)
app.use(function(req, res, next) {
console.log(res.headersSent) // <-- pay attention here
next()
})
// Import API Routes
app.use('/api', api)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
This route/page/index.vue will call the api/users
:
import axios from '~/plugins/axios'
export default {
async asyncData () {
let { data } = await axios.get('/api/users')
return { users: data }
},
head () {
return {
title: 'Users'
}
}
}
I added a console.log
in plugins/axios.js:
import * as axios from 'axios'
let options = {}
// The server-side needs a full url to works
if (process.server) {
options.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}`
console.log('express:' + options.baseURL)
}
export default axios.create(options)
When I run the app and access it on my browser at http://127.0.0.1:3000/:
In my terminal I get:
false
express:http://localhost:3000
false
false
false
false
false
false
false
false
As you can see that it has called api/users
8 times more after the first call.
Is it a bug in Nuxt?
If I removed app.use(nuxt.render)
from server/index.js:
// Give nuxt middleware to express
// app.use(nuxt.render)
And I access it at http://127.0.0.1:3000/ or http://127.0.0.1:3000/api/users, I get:
false
Just one call which is correct.
So, what is going on with Nuxt?
It's not a bug. Express is executing your middleware. In this case, they are http requests for client assets like
app.js
,logo.png
etc. Change your middleware code like below and check the console.