解决的跨域的方式有很多,站在前台的角度来讲,无论是vue还是uniapp,解决跨域的方法都是使用proxy代理的方式!请看下方解决步骤
<template>
<view class=""><button type="primary" @click="request">request</button></view>
</template>
<script>
export default {
methods: {
request() {
uni.request({
url: 'https://www.baidu.com/goods',
method: 'GET',
data: {},
success: res => {},
fail: () => {},
complete: () => {}
});
}
}
};
</script>
点击request按钮,我们会看到在浏览器上会报跨域错误的问题
?
?如何解决:
1.在manifest.json中添加以下代码
"h5": {
"devServer": {
"https": false,
"proxy": {
"/qianjue": {
"target": "https://www.baidu.com",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/qianjue": "/"
}
}
}
}
}
2.因为我们把?https://www.baidu.com代理成了 /qianjue?
故需要把请求的baseUrl全部更换为 /qianjue
<template>
<view class=""><button type="primary" @click="request">request</button></view>
</template>
<script>
export default {
methods: {
request() {
uni.request({
url: '/qianjue/goods',
method: 'GET',
data: {},
success: res => {},
fail: () => {},
complete: () => {}
});
}
}
};
</script>
重启再点击进行请求
?解决!
|