You need to have at least this in your
nuxt.config.js
file
export default {
ssr: true,
target: 'server',
modules: [
'@nuxtjs/axios',
],
serverMiddleware: [
{ path: '/api', handler: '~/server-middleware/rest.js' },
],
}
And a /server-middleware/rest.js
file with
const app = require('express')()
app.get('/what-is-my-name/:name', (req, res) => {
res.json({ name: req.params.name, age: 12 })
})
module.exports = app
Then, you can use it like this in any .vue
file
<template>
<div>
<input id="name" v-model="name" type="text" name="name" />
<button @click="callNuxtApi">try local Nuxt API</button>
<div>
Response from the backend:
<pre>{{ response }}</pre>
</div>
</div>
</template>
<script>
export default {
name: 'AccordionList',
data() {
return {
name: 'bob',
response: {},
}
},
methods: {
async callNuxtApi() {
const response = await this.$axios.$get(
`/api/what-is-my-name/${this.name}`
)
this.response = response
},
},
}
</script>
Then, this will successfully work locally (I’m using a dynamic name
here).
Then, you’ll need to deploy it on a VPS, but there is a small gotcha: you will need to deploy your app and push the server-middleware
directory yourself as explained here: https://github.com/nuxt/nuxt.js/issues/9158#issuecomment-820676790
Hence why, platform like Render.com or Heroku are probably not the easiest ones for this kind of task (I’m not even sure that this is possible).
Some homemade VPS or using Nuxt3 would probably be more easily overall IMO.