Vue3 使用 axios 实现跨域
Vue3 使用 axios 可以实现请求跨域问题
1.安装axios
npm install axios -S
2.引入axios 并配置为全局 $axios 对象
main.js
import { createApp } from 'vue' import App from './App.vue' import axios from 'axios' //createApp(App).mount('#app') const app = createApp(App) app.config.globalProperties.$axios = axios app.mount('#app')
2. 配置转发
下面代码是 将 127.0.0.1 的 8080端口 中凡是 含有 /sina 的地址 转发至 http://192.168.1.31:80/ 下
其中 /sina 不改变,只改变IP和端口
vue.config.js
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, //-----------------------Axios跨域请求----------------------------------------- devServer:{ port:8080,//vue网页访问的端口 host:"127.0.0.1",//vue网页访问的地址 https:false, open:false, proxy: { '/sina': { //为用于替换的的标识字符串 target: 'http://192.168.1.31:80/',//Axios跨域请求的IP changeOrigin: true, ws: true, pathRewrite: { '^/sina': '' //不改变 } }, /* 可以同步配置多个转发目标 '/phpUrl': { //为用于替换的的标识字符串 target: 'http://192.168.1.8:8080/VueApi',//Axios跨域请求的IP changeOrigin: true, ws: true, pathRewrite: { '^/phpUrl': '' //不用改 } } */ } } //---------------------------------------------------------------------------- })
调用方式
其中地址 /sina/api/sessions 转发前 实际请求地址是 http://127.0.0.1:8080/sina/api/sessions
因为地址中 含有 /sina 符合转发条件 因此 axios 进行转发
转发后 实际请求地址是 http://192.168.1.31:80/sina/api/sessions
这样就实现了用 axios 进行 跨域转发
且可以实现 当地址中不含 /sina 时正常请求,不进行转发
//axios 请求并 进行转发 ------------------------------------------------- //参数 var params=new URLSearchParams(); params.append('login',"admin"); params.append('password',"admin"); /**/ this.$axios.post('/sina/api/sessions', params) .then(response => { // 处理响应数据 console.log(response.data); this.current_call_token= response.data.token; console.log(this.current_call_token); }) .catch(error => { // 处理请求错误 console.log(error); });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2021-06-30 Springboot java项目 java.sql.SQLNonTransientConnectionException: CLIENT_PLUGIN_AUTH is required
2021-06-30 Spring boot 项目报错 javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;