本帖最后由 sdcsdv 于 2024-3-12 17:41 编辑
本帖最后由 sdcsdv 于 2024-3-12 16:40 编辑
计划通过拦截axios请求,实现跨域访问,但发现axios跨域先被浏览器抓到了,请教如何实现拦截跨域访问?
前端代码:
const onClick = async () => {
axios.get('https://www.baidu.com/', {})
.then(res => {
console.log(res);
})
.catch((e) => {
console.log('获取数据失败');
});
};
油猴代码:
// ==UserScript==
// @name ajaxHooker拦截-2024
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match http://localhost:5173/*
// @grant unsafeWindow
// @grant GM_xmlhttpRequest
// @connect *
// @require https://scriptcat.org/lib/637/1.3.3/ajaxHooker.js
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
ajaxHooker.hook(request => {
console.log('request:', request);
request.response = res => {
const responseText = res.responseText; // 注意保存原数据
res.responseText = new Promise(resolve => {
setTimeout(() => {
//跨域访问
GM_xmlhttpRequest({
url: request.url,
method: request.method,
headers: request.headers,
data: request.body,
onload: function(res) {
console.log('res:', res);
//返回修改后数据
resolve(res);
},
onerror: function(error) {
console.log('error:', error);
reject(error);
}
});
//resolve('test');
}, 2000);
});
};
});
})();