axios实现跨域三种方法

您所在的位置:网站首页 axios如何配置请求头 axios实现跨域三种方法

axios实现跨域三种方法

2023-12-12 15:34| 来源: 网络整理| 查看: 265

大家好,又见面了,我是你们的朋友全栈君。

问题背景

Axios是不允许跨域访问的,别说跨域,跨端口都不行。例如某项目我本地vue前端frontEnd为localhost:8889,Java后台 backEnd为localhost:8888

报错信息: Access to XMLHttpRequest at 'http://localhost:8888/cert/certCompany/list2' from origin 'http://localhost:8889' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

在这里插入图片描述在这里插入图片描述

axios请求代码:

axios.post('http://localhost:8888/cert/certCompany/list2',JSON.stringify(this.searchParam)) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error); });

这个时候就有两个方案了:

修改frontEnd前端,支持跨域(通过代理的形式,当然这种是伪跨域,但是挺有用,前提是后端不限制即可)。修改backEnd后台,支持跨域(同时限制可跨域名,不在本文讨论范围,且看过往处理方式): SpringBoot之跨域过滤器配置允许跨域访问 SpringCloudApiGateway之支持Cors跨域请求解决方案main.js

引入axios

//引入axios by zhengkai.blog.csdn.net import axios from 'axios' Vue.prototype.$axios = axios axios.defaults.baseURL = '/api' //自动附加在所有axios请求前面,则可以省略/api,直接写'/xxxx/xxx'。否则需要设置'/api/xxxx/xxx'config.index.js

改造proxyTable部分,引入虚拟代理 ,请求target这个地址的时候直接写成/api即可。

dev: { env: require('./dev.env'), port: 8889, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { //axios跨域改造 by zhengkai.blog.csdn.net '/api': { target:'http://localhost:8888/cert/', // 你请求的第三方接口 changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题 pathRewrite:{ // 路径重写, '^/api': '' // 替换target中的请求地址,也就是说/api=/target,请求target这个地址的时候直接写成/api即可。 } } }, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false }业务.vue

修改请求为/api封装开头(但是如果你的借口包含/api的关键字的话,建议使用其他关键字)

//axios跨域请求改造 by zhengkai.blog.csdn.net axios.post('/certCompany/list2',JSON.stringify(this.searchParam)) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });验证效果

请求不报错,没有烦人的No 'Access-Control-Allow-Origin' header is present on the requested resource.报错。

在这里插入图片描述在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/194644.html原文链接:https://javaforall.cn



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3