Vuejs+Nodejs学习笔记(1)——前后端连接方法

本文介绍了如何通过axios解决前端到后端的跨域问题,包括前端使用axios发送请求,后端通过CORS处理响应。同时详细讲解了在Vue项目中配置axios和后端使用Express、MySQL进行数据库操作的步骤。
摘要由CSDN通过智能技术生成

在这里插入图片描述

前端到后端的跨域问题需要通过axios来解决,而后端的跨域问题需要通过cros来解决。

1 前端配置

前端发送登录请求到后端,后端匹配用户名和密码,匹配成功后回传code和token,前端接收到token后进入下一级菜单。

1.1 安装axios

命令行输入:

npm install axios

1.2 js代码

配置JS代码,导入axios,然后使用axios.get()、axios.post()、axios.put()、axios.get()等。

// Login.vue
// ...
<script>
// ...
import axios from 'axios';
export default{
	// ...
	axios.get(`http://localhost:3000/userInfo/search?username=${loginInfo.username}&pwd=${loginInfo.password}`
	).then(res =>{
		console.log(res.data);
		if(res.data.token != ""){
			router.push("home");
		}else{
			console.log("账号或密码错误");
		}
	}).catch(err =>{
		console.log(err);
	})
}
</script>

1.3 配置反向代理

进入vite.config.js文件,添加server设置:

export default defineConfig({
	// ... 
	server:{
		proxy:{
			'/api':{
	        target:'localhost',
	        changeOrigin:true
			}
		}
	}
});

2 后端配置

后端接收到前端发送的HTTP请求后,需要连接数据库查找信息。

2.1 安装包

安装cors、express、mysql、mysql2、sequelize、nodemon。

2.2 数据库配置文件

//dbconfig.js
const Sequelize = require('sequelize');

// 创建一个新的Sequelize实例
const DB = new Sequelize("test_db","root","root",{ //分别为数据库名、用户名、密码
    host:'localhost',
    port: 3306,
    dialect:'mysql',
    timezone: '+8:00',
    // dialectOptions: {
    //     useUTC: false
    // },
    pool:{
        max:10,
        min:0,
        idle:10000, // 10秒没有使用,释放该连接
    },
    logging:console.log,   //Sequelize日志输出方法
})

// 测试数据库连接
DB.authenticate().then(()=>{
    console.log("数据库连接成功");
}).catch((err)=>{
    console.log("数据库连接失败: ",err)
});

module.exports = DB;

2.3 添加后端与数据库连接的模型文件

// user_info_model.js
const DB = require("../config/dbconfig.js");
const Sequelize = require('sequelize');

// user_login是数据库的表名 define('表名',{字段})
// 模型与数据库表名的映射
const user_info_model = DB.define("user_info",{
    id:{
        primaryKey: true,
        type: Sequelize.INTEGER,
        field:"user_id",
        autoIncrement:true
    },
    username:{
        type:Sequelize.STRING(45),
        allowNull:true,
        field:"username"
    },
    password:{
        type:Sequelize.STRING(30),
        allowNull:true,
        field:"password"
    },
},{
    freezeTableName: true,      // 防止程序自动在表名后加s
    timestamps: false           // 禁用createAt和updateAt
});

module.exports = user_info_model;

2.4 添加路由信息

这里可以实现读取前端发来的信息,并与数据库内元素进行比对,返回前端所需要的token。

//user_info.js
const express = require('express');
const router = express.Router();
const user_info_model = require("../Models/user_info_model.js");
const { Sequelize } = require('sequelize');
const Op = Sequelize.Op;
var token = "";

router.get('/', (req, res, next) => {
    res.send("hello world");
});

// 获取user信息:http://localhost:3000/userInfo/search?username=xxxx&pwd=xxxx
router.get('/search', async (req, res, next) => {
    try {
        const result = await user_info_model.findAll({
            where:{username: req.query.username}
        }).then(users =>{
            if(users.length > 0){
                for(i in users){
                    if(req.query.pwd === users[i].password){
                        console.log("用户名和密码匹配");
                        token = "yes";
                        res.json({code: 1000,token:token});
                        break;
                    }
                }
                if(!token){
                    console.log("密码错误或未授权");
                    res.json({code: 1002});
                }
            }else{
                console.log('用户名、电话号码或电子邮件不存在');
                res.json({code: 1001});
            }
        });
    } catch (err) {
        next(err);
    }
});

// 错误处理中间件
router.use((err, req, res, next) => {
    console.error(err);
    res.status(500).json({
        code: 1002,
        msg: '服务器发生错误',
    });
});

module.exports = router;
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.jsVue.js都是非常流行的前端和后端技术。为了连接这两个技术,我们可以采用以下步骤: 1. 开发后端: 使用Node.js构建后端服务,提供API接口。可以使用任何适合的框架,比如Express、Koa等。 2. 安装CORS: 在Node.js中安装cors以允许跨域资源共享,因为我们将会从vue前端连接到后端Node.js服务。 3. 开发前端: 使用Vue.js构建前端,可以使用Vue CLI或者其他适当的方式。使用vue-router轻松构建应用程序路由系统。 4. 连接前后端: 使用Axios或fetch来调用API接口,从Node.js后端获取数据并将其显示在Vue.js前端。 在Vue中,我们可以定义axios来发送异步HTTP请求。我们可以发送GET、POST、PUT等HTTP请求。比如,我们可以定义一个从后端获取数据的axios实例: ``` javascript import axios from 'axios'; const instance = axios.create({ baseURL: 'http://localhost:3000/api', // 后端接口地址 }); export default instance; ``` 然后,在Vue组件中,我们可以使用这个实例来发送HTTP请求。举个例子,我们可以获取用户列表: ``` javascript <script> import api from '@/services'; export default { data() { return { users: [], }; }, created() { api.get('/users') .then(response => { this.users = response.data; }) .catch(error => { console.log(error); }); }, }; </script> ``` 在这个例子中,我们使用Axios从后端Node.js服务获取用户列表,然后将它保存在Vue.js的数据中。这样,在前端页面上就可以显示这些用户了。 综上,这是使用Node.jsVue.js连接前后端的一些简单步骤。有了这个基础知识,我们可以更深入的学习和应用这两个技术来构建更好的Web应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值