0👍
you have 2 options put togheter express and Nuxt, making live express in the server directory or use nuxt pure as frontend (awesomesite.com) and express pure as api (api.awesomesite.com), in any of the two cases the life is more easy if you use axios and configure them in your nuxt.config.js file,
axios: {
baseURL: process.env.AXIOS_SERVER
// See https://github.com/nuxt-community/axios-module#options
},
after that you use axios as usual in your components to communicate with the server side.
I thing you try to use express embed with nuxt. To do that i prefers create a structure inside server directory
/server
/router
index.js
index.js
globals.js
router/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()
in a vue component you can use AXIOS simply like that:
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
}
}
Source:stackexchange.com