目录

vite proxy 解决跨域问题

 fetch

代码演示

Post请求

Get请求

Axios

安装

代码演示

Post请求

Get请求


vite proxy 解决跨域问题

为什么会出现跨域问题?

浏览器的同源策略

首先给出浏览器“同源策略”的一种经典定义,同源策略限制了来自不同源(相对于当前页面而言)的document或script,对当前document的某些属性进行读取或是设置,举例来说,A网站(www.aaa.com)上有某个脚本,在B网站(www.bbb.com)未曾加载该脚本时,该脚本不能读取或是修改B网站的DOM节点数据

解决办法

 代码演示

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/, ""),} }}})

 运行结果 

 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

用户页面

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);});},},};

运行效果

Get请求

后端接口展示

 user.vue

用户页面

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);});}};

运行结果

Axios

官网

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

axios优点:

  1. 支持node端和浏览器端
  2. 支持 Promise
  3. 丰富的配置项

安装

使用 npm:

$ npm install axios

查看是否安装成功

代码演示

Post请求

后端接口演示

User.vue 

用户页面

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);});},},};

运行结果

Get请求

后端接口演示

User.vue

用户页面

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("总是会执行");});},};

 运行结果