赞
踩
初级应用。实现目标:结合VUE项目 和 flask 后台服务实现简单的用户登录功能。
博主使用的MYSQL 8.0
@vue/cli 5.0.8
前端页面
vue create your-project-name
npm install axios
- <template>
- <div>
- <h1>登录</h1>
- <form @submit.prevent="login">
- <input type="text" v-model="user.username" placeholder="用户名">
- <input type="password" v-model="user.password" placeholder="密码">
- <button type="submit">提交</button>
- </form>
- </div>
- </template>
-
- <script>
- import axios from 'axios';
-
- export default {
- data() {
- return {
- user: {
- username: '',
- password: ''
- }
- };
- },
- methods: {
- login() {
- axios.post('http://127.0.0.1:5000/login', this.user)
- .then(response => {
- // 登录成功
- alert(response.data.message);
- })
- .catch(error => {
- if (error.response) {
- // 登录失败
- alert(error.response.data.message);
- } else {
- // 网络或其他错误
- console.error("请求失败:", error);
- }
- });
- }
- }
- };
- </script>
后端代码
- # app.py
-
- from flask import Flask, jsonify, request
- from flask_cors import CORS
- from flask_httpauth import HTTPBasicAuth
-
- app = Flask(__name__)
- CORS(app) # 允许跨域
- auth = HTTPBasicAuth()
-
- # 假设的用户数据库记录
- users = {
- "admin": "123456"
- }
-
- @auth.verify_password
- def verify_password(username, password):
- if username in users and users[username] == password:
- return username
-
- @app.route('/login', methods=['POST'])
- def login():
- data = request.json
- if not data or not data.get('username') or not data.get('password'):
- return jsonify({"message": "必须提供用户名和密码", "status": "error"}), 400
-
- username = data.get('username')
- password = data.get('password')
-
- if verify_password(username, password):
- return jsonify({"message": "登录成功,这里是flask后台", "status": "success"})
- else:
- return jsonify({"message": "用户名或密码错误", "status": "error"}), 401
-
- if __name__ == '__main__':
- app.run(debug=True)
- from flask import Flask, request, jsonify
- from flask_sqlalchemy import SQLAlchemy
- from flask_cors import CORS
-
- app = Flask(__name__)
- CORS(app) # 允许跨域
-
- # 数据库设置
- app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost/operationdb'
- app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
- db = SQLAlchemy(app)
-
- # 用户模型
- class User(db.Model):
- __tablename__ = 'table_users'
- id = db.Column(db.Integer, primary_key=True)
- username = db.Column(db.String(255), unique=True, nullable=False)
- password = db.Column(db.String(255), nullable=False)
-
- # 登录路由
- @app.route('/login', methods=['POST'])
- def login():
- data = request.get_json()
- username = data.get('username')
- password = data.get('password')
-
- user = User.query.filter_by(username=username, password=password).first()
-
- if user:
- return jsonify({"message": "登录成功,data版后台", "status": "success"}), 200
- else:
- return jsonify({"message": "用户名或密码错误", "status": "error"}), 401
-
- if __name__ == '__main__':
- app.run(debug=True)
vue项目文件内启动: npm run serve
启动后台文件: python XXXX.py
前端:
提交后效果:
可以看到返回的message弹窗,访问数据库成功。
提示:在后台搭建中一定不能忘记 CORS,否者会出现跨域拒绝访问的问题。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。