2017-08-31 77 views
1

为什么Nuxt多次拨打服务器 on single route/page?在单个路由/页面上多次调用服务器的Nuxt/Vue缺陷?

下面是我从他们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' 
    } 
    } 
} 

我加了一个console.logplugins/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) 

当我运行应用程序和acc ESS它在我的浏览器在http://127.0.0.1:3000/

在我的终端,我得到:

false 
express:http://localhost:3000 
false 
false 
false 
false 
false 
false 
false 
false 

正如你可以看到,它已经呼吁api/users8倍第一电话后更多

这是一个错误在Nuxt?

如果我删除app.use(nuxt.render)server/index.js

// 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发生了什么?

回答

1

这不是一个错误。 Express正在执行你的中间件。在这种情况下,它们是客户端资产的http请求,如app.js,logo.png等。更改您的中间件代码,如下所示,并检查控制台。

app.use(function(req, res, next) { 
    console.log(req.url) // Change this line 
    next() 
}) 
相关问题