I did research on how Vue in a Nuxt project interacts with Express, and figured out the relationship. Here are some tips to start an Express project with Nuxt.js. First of all, let’s take a look at your Nuxt version to see if it is supported.
<article class="post-item">
<h2 class="post-title"><a href="/welcome/">Welcome to Ghost</a></h2>
<p>Welcome, it's great to have you here...</p>
<a class="read-more" href="/welcome/">Read more</a>
</article>
For your information, my current version is v2.4.2.
Navigation to “Hello World”
- Create a Nuxt project
npx create-nuxt-app <project-name>
- Create anapiFolder in the project root.
- Create an index.js in the folder with the following code.
const app = require('express')()module.exports = { path: '/api', handler: app }
app.get('/hello', (req, res) => { console.log('hello nuxt in text') res.send('world')})
NOTE!!
Notice, there is no /api prefix in the app.get(), above. This is because in module.exports we already specified the “global” prefix as /api for this whole express router instance.
This means to set the global path for “app.get” followed by /api.
Add serverMiddleware in nuxt.config.js
- Make sure the property is NOTmiddleware
serverMiddleware: ['~/api/index.js'],
Reboot by adding the above code. The added severMiddleware file is not watch target. Manually, add the file to “watch” property or simply reboot Nuxt.
- Access to localhost:3000/api/hello andworld will appear in the browser, which means success.
- Certainly, an output called console.log(‘hello nuxt in text’)will not appear in browser console, but in the terminal console.
Welcome onboard! You’ve got connection to Vue and Express. Just access to localhost:3000/api/hello , or obtain json or other content via Express on your own API.