当前位置:网站首页>跨域解决方案
跨域解决方案
2022-08-05 00:49:00 【shewlong】
使用proxy解决跨域问题
问题引入
前端如果不通过proxy设置代理,则请求接口会报跨域问题
Access to XMLHttpRequest at 'https://www.baidu.com/s?ie=utf+-+8&mod=1&isbd=1&isid=28B087E526051712&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=this.$axios&fenlei=256&oq=this.%2524axios&rsv_pq=af3009be00003a79&rsv_t=1c5fWtMk%2B6xwWKQqibPt6DyyGzLEaQSdASvH93Q6UDEXyZdfGTnRxojuNms&rqlang=cn&rsv_enter=0&rsv_dl=tb&rsv_btype=t&bs=this.$axios&_ss=1&clist=&hsug=&f4s=1&csor=' from origin 'http://172.16.20.231:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方案
1.在vue.config.ts中进行配置
//vue-cli3.0 里面的 vue.config.js做配置
devServer: {
proxy: {
'/cdn': {
target: 'https://position.csdnimg.cn', // 后台接口域名
ws: true, //如果要代理 websockets,配置这个参数
secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, //是否跨域
pathRewrite:{
'^/cdn': '/'
}
}
}
}
2.在具体页面发送请求
假设要请求的后端地址为’https://position.csdnimg.cn/oapi/get’
//使用axios进行请求,首先在main.ts中将axios挂载到vue原型中
import axios from 'axios'
Vue.prototype.$service = axios
//在具体页面中使用this.$axios进行请求,原生未进行封装
this.$axios({
method: "get",
//上面的proxy会将url地址解析为https://position.csdnimg.cn/oapi/get
url: "/cdn/oapi/get",
params: {
// 这里是发送给后台的数据
},
}).then((response) => {
// 这里使用了ES6的语法
console.log(response); // 请求成功返回的数据
});
3.某些条件下可能需要对地址进行替换
var url = "https://position.csdnimg.cn/oapi/get"
var reg = /^http(s)?:\/\/(.*?)\//
// 必须是http开头或者https开头,结尾为'/'
// 把host替换成指定数值
var ToReplace = 'cdn/'
url.replace(reg, ToReplace)
// Host/cench
//*******************************************
如果只需要取出例如:position.csdnimg.cn,则通过以下方式
reg.exec(url)[2]
// www.cnblogs.com
边栏推荐
猜你喜欢
金九银十面试跳槽季;你准备好了吗?
gorm joint table query - actual combat
Inter-process communication and inter-thread communication
How DHCP works
Bit rate vs. resolution, which one is more important?
oracle create tablespace
MongoDB construction and basic operations
内存取证系列1
5.PCIe官方示例
"WEB Security Penetration Testing" (28) Burp Collaborator-dnslog out-band technology
随机推荐
ORA-01105 ORA-03175
E - Distance Sequence (prefix and optimized dp
C# const readonly static 关键字区别
leetcode: 269. The Martian Dictionary
Lattice PCIe Learning 1
2022牛客多校第三场 J题 Journey
JUC线程池(一): FutureTask使用
软件测试面试题:您如何看待软件过程改进?在您曾经工作过的企业中,是否有一些需要改进的东西呢?您期望的理想的测试人员的工作环境是怎样的?
ORA-00257
Software testing interview questions: test life cycle, the test process is divided into several stages, and the meaning of each stage and the method used?
Software Testing Interview Questions: What's the Key to a Good Test Plan?
自定义线程池
Software testing interview questions: What is the difference between load testing, capacity testing, and strength testing?
EL定时刷新页面中的皕杰报表实例
could not build server_names_hash, you should increase server_names_hash_bucket_size: 32
Bit rate vs. resolution, which one is more important?
OPENWIFI实践1:下载并编译SDRPi的HDL源码
2021年11月网络规划设计师上午题知识点(上)
After the staged testing is complete, have you performed defect analysis?
2022杭电多校 第三场 B题 Boss Rush