Vue3 Nodejs后台搭建
    		       		warning:
    		            这篇文章距离上次修改已过446天,其中的内容可能已经有所变动。
    		        
        		                
                在搭建Vue3和Node.js后端时,你可以使用以下步骤:
- 安装Node.js环境。
- 创建Vue3项目: - npm create vue@latest- 选择Vue3,并且按照提示填写项目信息。 
- 进入项目目录,并启动Vue3项目: - cd <project-name> npm run dev
- 安装Express.js: - npm install express --save
- 在项目根目录下创建一个名为 - server.js的文件,并写入以下代码:- const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server running on port ${port}`); });
- 启动Node.js后端服务器: - node server.js
- 配置Vue3项目以支持前后端分离开发,例如使用代理来将API请求转发到Node.js服务器。修改 - vue.config.js文件:- module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, pathRewrite: { '^/api': '' } } } } };
- 在Vue3项目中发送API请求,例如使用Axios: - // 安装Axios npm install axios // 在Vue组件中使用Axios import axios from 'axios'; export default { async mounted() { try { const response = await axios.get('/api/data'); console.log(response.data); } catch (error) { console.error(error); } } };
以上步骤为你提供了搭建Vue3和Node.js后端的基本框架。你可以根据实际需求,在此基础上添加更多功能,例如数据库连接(如使用MongoDB或MySQL),API路由,认证等。
评论已关闭