我如何使用下面的示例代码:
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
app.get('/route', (req, res) => { // i test this, but failed
res.json({ message: 'yes' }) // then on .vue feel i use axios to get this localhost
})
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()我应该在start函数中创建一些路由器吗?如何将它们导出为nuxt并获取.vue文件中的数据?
发布于 2019-03-26 23:54:00
你有两个选择,把togheter express和Nuxt放在服务器目录中,或者使用nuxt纯作为前端(awesomesite.com)和express纯作为api (api.awesomesite.com),在这两种情况中的任何一种情况下,如果你使用axios并在你的nuxt.config.js文件中配置它们,生活会更容易。
axios: {
baseURL: process.env.AXIOS_SERVER
// See https://github.com/nuxt-community/axios-module#options
},之后,您可以像往常一样在组件中使用axios与服务器端通信。
我认为你尝试使用带有nuxt的express embed。为此,我更喜欢在服务器目录中创建一个结构
/server
/router
index.js
index.js
globals.js路由器/index.js
const router = require('express').Router()
router.post('/your-route', function (req, res, next) {
//todo this route
});
router.post('/other-route', function (req, res, next) {
//todo this route
});
module.exports.router = router;server/index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
{ router } = require('./router') //the router!!!
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
app.use('/', router) // '/' or '/api' depends to you
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()在vue组件中,您可以像这样简单地使用AXIOS:
methods: {
async send() {
this.waiting = true
await this.$axios({
method: 'post',
url: '/your-route',
data: this.form
})
.then(res => {
this.success = true
this.error = false
this.onReset()
})
.catch(e => {
this.error = true
this.success = false
})
this.waiting = false
}
}https://stackoverflow.com/questions/55357856
复制相似问题