为什么 Nuxt 在单个路由/页面上调用服务器这么多多次?
下面是我从他们的 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
这个route/page/index.vue将调用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'
}
}
}
我在plugins/axios.js中添加了一个console.log
:
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)
当我运行应用程序并在浏览器上访问它时 http://127.0.0.1:3000/ :
在我的终端中我得到:
false
express:http://localhost:3000
false
false
false
false
false
false
false
false
正如您所看到的,在第一次调用之后,它又调用了 api/users
8 次。
这是 Nuxt 中的错误吗?
如果我从 server/index.js 中删除了 app.use(nuxt.render)
:
// Give nuxt middleware to express
// app.use(nuxt.render)
我可以通过 http://127.0.0.1:3000/ 访问它或http://127.0.0.1:3000/api/users ,我得到:
false
只有一个调用是正确的。
那么,Nuxt 发生了什么?
最佳答案
这不是一个错误。 Express 正在执行您的中间件。在本例中,它们是对客户端资源(如 app.js
、logo.png
等)的 http 请求。如下所示更改您的中间件代码并检查控制台。
app.use(function(req, res, next) {
console.log(req.url) // Change this line
next()
})
关于node.js - Nuxt/Vue 在单个路由/页面上多次调用服务器的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45979000/