question
There is a cross-domain problem when using Tencent map sdk or webService api h5 in the project
Solution
1. Implement a jsonp function
Principle: Dynamically generate a JavaScript tag whose src is concatenated by the interface url, request parameters, and callback function name, and realize cross-domain requests by using the feature of js tags without cross-domain restrictions.
const jsonp = function(url, data) {
return new Promise((resolve, reject) => {
// 1.初始化url
let dataString = url.indexOf('?') === -1 ? '?' : '&'
let callbackName = `jsonpCB_${
Date.now() }`;
url += `${
dataString }callback=${
callbackName }`
if(data) {
// 2.有请求参数,依次添加到url
for(let k in data) {
url += `&${
k }=${
data[k] }`
}
}
let scriptNode = document.createElement('script');
scriptNode.src = url;
// 3. callback
window[callbackName] = (result) => {
result ? resolve(result) : reject('没有返回数据');
delete window[callbackName];
document.body.removeChild(scriptNode);
}
// 4. 异常情况
scriptNode.addEventListener('error', () => {
reject('接口返回数据失败');
delete window[callbackName];
document.body.removeChild(scriptNode);
}, false)
// 5. 开始请求
document.body.appendChild(scriptNode)
})
}
2. Initiate a request, you need to pay attention to the output: jsonp in the parameter , you can also write it as promise then, refer to the original blog click here
async function getData() {
let res = await jsonp('https://apis.map.qq.com/ws/location/v1/ip',{
key: "xxxxxxx",
output: "jsonp"
});
console.log(res);
}
getData();
Otherwise an error will occur:
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://apis.map.qq.com/ws/location/v1/ip?callback=jsonpCB_1626785944415&key=xxxxxx with MIME type application/json.
3. In this way, the cross-domain problem can be solved without using the vue-jsonp dependency package
The general structure of the article refers to this blog