简体   繁体   中英

How to use nuxt.js with node and expressjs

我正在使用 node 和 express 作为后端制作一个简单的注册/登录 API,但我想知道如何使用 nuxt 作为前端连接到我的 API 端点,以便我可以部署我的节点应用程序

First thing is, you need to move to your nuxt.config.js and you need to tell nuxt witch routes are for viewing content and witch are just API endpoints. For that there is a option called serverMiddleware

serverMiddleware: [
   '~/api/index.js'
],

Now you need to create an Folder in your root directory called api and inside the api folder there you should create an file called index.js , that will be your express.js server.

The index.js looks like this:

 const express = require('express')
 const app = express()

 app.get("/test", (req, res) => {
    res.status(200).json({ message: "I work" });
 })

 module.exports = {
  path: '/api',
  handler: app
 }

Dont forget to install express npm i express After that you need to restart your server. If you navigate now to localhost:3000/api/test you should see I work

I have also found out if you make for example a mistake, nuxt will tell you 404 cant find that page . For example you write const express = require("express") but you forget to install it via npm i express , nuxt will just throw error 404 without saying that you dont installed express

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM