vue 获取后端数据(vue获取后端数据 存入pinia)
ztj100 2024-11-02 14:31 29 浏览 0 评论
proxy 解决请求出错问题
为什么会出现跨域问题?
浏览器的同源策略
首先给出浏览器“同源策略”的一种经典定义,同源策略限制了来自不同源(相对于当前页面而言)的document或script,对当前document的某些属性进行读取或是设置,举例来说,A网站(www.aaa.com)上有某个脚本,在B网站(www.bbb.com)未曾加载该脚本时,该脚本不能读取或是修改B网站的DOM节点数据。
本地测试解决请求办法
vite
代码演示
vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
//中转服务器
server:{
//通过代理实现跨域 http://localhost:20219
proxy:{
'/api':{
//替换的服务器地址
target: 'http://localhost:20219',
//开启代理 允许跨域
changeOrigin: true,
//设置重写的路径
rewrite: (path) => path.replace(/^\/api/, ""),
}
}
}
})
运行结果
Vue CLI
代码演示
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
//通过代理实现跨域
proxy: {
'/path':{
//替换的服务器地址
target: 'https://localhost/prod-api',
//开启代理 允许跨域
changeOrigin: true,
//设置重写的路径
pathRewrite:{
'^/path':''
}
}
}
}
})
运行结果
fetch
Fetch API 提供了一个获取资源的接口(包括跨域请求)。任何使用过 XMLHttpRequest 所有人都能轻松上手,而且新的 API 提供了更强大和灵活的功能集。
优点:
1. 语法简洁,更加语义化
2. 基于标准 Promise 实现,支持 async/await
3. 同构方便,更加底层,提供的API丰富(request, response, body , headers)4. 脱离了XHR,是ES规范里新的实现方式复制代码
缺点:
1. fetch只对网络请求报错,对400,500都当做成功的请求,服务器返回 400,500 错误码时并不会 reject。
2. fetch默认不会带cookie,需要添加配置项: credentials: 'include'。
3. fetch不支持abort,不支持超时控制,造成了流量的浪费。
4. fetch没有办法原生监测请求的进度,而XHR可以
代码演示
Post请求
后端接口展示
user.vue
<template>
<h2>用户页面</h2>
<button @click="userLogin">登入</button>
</template>
<script>
export default {
data() {
return {
user: {
userTelephone: 12244332222,
userPassword: "123456"
},
};
},
//fetch 原生js 是http数据请求的一种方式
//fetch 返回promise对象
methods: {
userLogin() {
fetch("api/user/userLoginByPassword", {
method: "post",
body: JSON.stringify({
userPassword: this.user.userPassword,
userTelephone: this.user.userTelephone
}),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
console.log(res);
//json()将响应body 解析json的promise
// console.log(res.json());
return res.json();
})
.then((res) => {
console.log(res);
});
},
},
};
</script>
运行效果
编辑Get请求
后端接口展示
user.vue
<template>
<h2>用户页面</h2>
</template>
<script>
export default {
//fetch 原生js 是http数据请求的一种方式
//fetch 返回promise对象
created() {
//获取验证图片
fetch("/api/user/toCreateVerifyImg", {
method: "get"
})
.then((res) => {
console.log(res);
//json()将响应body 解析json的promise
// console.log(res.json());
return res.json();
})
.then((res) => {
console.log(res);
});
}
};
</script>
运行结果
Axios
官网:Axios API | Axios 中文文档 | Axios 中文网 (axios-http.cn)
Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
axios优点:
支持node端和浏览器端 支持 Promise 丰富的配置项
安装
使用 npm:
$ npm install axios
查看是否安装成功
代码演示
Post请求
后端接口演示
User.vue
<template>
<h2>用户页面</h2>
<button @click="userLogin">登入</button>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
user: {
userTelephone: 12244332222,
userPassword: "123456",
},
};
},
methods: {
//登入
userLogin() {
axios
.post("api/user/userLoginByPassword", {
userPassword: this.user.userPassword,
userTelephone: this.user.userTelephone,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
},
},
};
</script>
运行结果
Get请求
后端接口演示
User.vue
<template>
<h2>用户页面</h2>
</template>
<script>
import axios from "axios";
export default {
created() {
//获取验证图片
axios
.get("api/user/toCreateVerifyImg")
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// 总是会执行
console.log("总是会执行");
});
},
};
</script>
运行结果
TS 封装Axios
代码演示
request index.ts
import axios from "axios";
//创建axios实例
const service=axios.create({
//url开头
baseURL:"path",
timeout: 5000,
//请求头配置
headers:{
"Content-Type": "application/json; charset=utf-8"
}
})
//请求拦截
service.interceptors.request.use((config)=>{
//请求头放token
config.headers=config.headers || {}
if(localStorage.getItem('token')){
config.headers.Authorization=localStorage.getItem('token') || ""
}
return config;
})
//响应拦截
service.interceptors.response.use((res)=>{
const code:number=res.data.code
// 如果响应code不为200拦截掉
if(code!=200){
return Promise.reject(res.data)
}
return res.data;
},(err)=>{
// 打印错误请求
console.log(err);
})
export default service
request api.ts
import service from ".";
//登入接口
interface LoginData{
userTelephone:string,
userPassword:string
}
export function login(data:LoginData){
return service({
url:"/user/userLoginByPassword",
method: "post",
data
})
}
LoginView.vue 部分使用代码 想看=>完整版(登入功能实现)
//调用登入接口
login(data.ruleForm).then((res) => {
console.log(res)
localStorage.setItem("token", res.data.token);
router.push("/");
});
demo案例
- 感兴趣的可以了解了解(附源码)
- 上一篇:vue进阶(vue进阶知识点)
- 下一篇:vue常见面试题(vue面试题知识点大全)
相关推荐
- sharding-jdbc实现`分库分表`与`读写分离`
-
一、前言本文将基于以下环境整合...
- 三分钟了解mysql中主键、外键、非空、唯一、默认约束是什么
-
在数据库中,数据表是数据库中最重要、最基本的操作对象,是数据存储的基本单位。数据表被定义为列的集合,数据在表中是按照行和列的格式来存储的。每一行代表一条唯一的记录,每一列代表记录中的一个域。...
- MySQL8行级锁_mysql如何加行级锁
-
MySQL8行级锁版本:8.0.34基本概念...
- mysql使用小技巧_mysql使用入门
-
1、MySQL中有许多很实用的函数,好好利用它们可以省去很多时间:group_concat()将取到的值用逗号连接,可以这么用:selectgroup_concat(distinctid)fr...
- MySQL/MariaDB中如何支持全部的Unicode?
-
永远不要在MySQL中使用utf8,并且始终使用utf8mb4。utf8mb4介绍MySQL/MariaDB中,utf8字符集并不是对Unicode的真正实现,即不是真正的UTF-8编码,因...
- 聊聊 MySQL Server 可执行注释,你懂了吗?
-
前言MySQLServer当前支持如下3种注释风格:...
- MySQL系列-源码编译安装(v5.7.34)
-
一、系统环境要求...
- MySQL的锁就锁住我啦!与腾讯大佬的技术交谈,是我小看它了
-
对酒当歌,人生几何!朝朝暮暮,唯有己脱。苦苦寻觅找工作之间,殊不知今日之事乃我心之痛,难道是我不配拥有工作嘛。自面试后他所谓的等待都过去一段时日,可惜在下京东上的小金库都要见低啦。每每想到不由心中一...
- MySQL字符问题_mysql中字符串的位置
-
中文写入乱码问题:我输入的中文编码是urf8的,建的库是urf8的,但是插入mysql总是乱码,一堆"???????????????????????"我用的是ibatis,终于找到原因了,我是这么解决...
- 深圳尚学堂:mysql基本sql语句大全(三)
-
数据开发-经典1.按姓氏笔画排序:Select*FromTableNameOrderByCustomerNameCollateChinese_PRC_Stroke_ci_as//从少...
- MySQL进行行级锁的?一会next-key锁,一会间隙锁,一会记录锁?
-
大家好,是不是很多人都对MySQL加行级锁的规则搞的迷迷糊糊,一会是next-key锁,一会是间隙锁,一会又是记录锁。坦白说,确实还挺复杂的,但是好在我找点了点规律,也知道如何如何用命令分析加...
- 一文讲清怎么利用Python Django实现Excel数据表的导入导出功能
-
摘要:Python作为一门简单易学且功能强大的编程语言,广受程序员、数据分析师和AI工程师的青睐。本文系统讲解了如何使用Python的Django框架结合openpyxl库实现Excel...
- 用DataX实现两个MySQL实例间的数据同步
-
DataXDataX使用Java实现。如果可以实现数据库实例之间准实时的...
- MySQL数据库知识_mysql数据库基础知识
-
MySQL是一种关系型数据库管理系统;那废话不多说,直接上自己以前学习整理文档:查看数据库命令:(1).查看存储过程状态:showprocedurestatus;(2).显示系统变量:show...
- 如何为MySQL中的JSON字段设置索引
-
背景MySQL在2015年中发布的5.7.8版本中首次引入了JSON数据类型。自此,它成了一种逃离严格列定义的方式,可以存储各种形状和大小的JSON文档,例如审计日志、配置信息、第三方数据包、用户自定...
你 发表评论:
欢迎- 一周热门
-
-
MySQL中这14个小玩意,让人眼前一亮!
-
旗舰机新标杆 OPPO Find X2系列正式发布 售价5499元起
-
【VueTorrent】一款吊炸天的qBittorrent主题,人人都可用
-
面试官:使用int类型做加减操作,是线程安全吗
-
C++编程知识:ToString()字符串转换你用正确了吗?
-
【Spring Boot】WebSocket 的 6 种集成方式
-
PyTorch 深度学习实战(26):多目标强化学习Multi-Objective RL
-
pytorch中的 scatter_()函数使用和详解
-
与 Java 17 相比,Java 21 究竟有多快?
-
基于TensorRT_LLM的大模型推理加速与OpenAI兼容服务优化
-
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)