需求:发起一个请求,请求到服务器上的图片,显示在前端界面
服务器图片:http://www.intmote.com/star.png
写代码:直接请求服务器接口的时候
methods: {
getList() {
uni.downloadFile({
url: 'http://www.intmote.com/star.png',
success: (res) => {
console.log(res);
this.imageSrc = res.tempFilePath;
uni.hideLoading();
},
fail: (err) => {
console.log('downloadFile fail, err is:', err)
}
})
}
}
会发现控制台报错,遇到了跨域的问题了
那么前端该怎么去解决跨域问题?
想到之前写vue项目的时候,遇到过一次
https://cloud.tencent.com/developer/article/1423900
而uniapp是基于vue的,那么解决办法应该也是差不多的
1:打开manifest.json文件,选择源码视图,在里面添加proxy代理
"devServer": {
"proxy": {
"/api": {
"target":"http://www.intmote.com",
"changeOrigin": true,//是否跨域
"secure": false,// 设置支持https协议的代理
"pathRewrite":{"^/api":"/"}
}
}
},
2:回到当前页面,修改请求路径
uni.downloadFile({
url: '/api/star.png',
success: (res) => {
console.log(res);
this.imageSrc = res.tempFilePath;
uni.hideLoading();
},
fail: (err) => {
console.log('downloadFile fail, err is:', err)
}
})
3:当前页面完整代码(仅供参考)
<template>
<view>
<view class="uni-padding-wrap uni-common-mt">
<image class="img" v-if="imageSrc" :src="imageSrc" mode="center" />
</view>
</view>
</template>
<script>
export default {
data() {
return {
imageSrc: ''
}
},
onLoad() {
this.getList();
},
methods: {
getList() {
uni.downloadFile({
url: '/api/star.png',
success: (res) => {
console.log(res);
this.imageSrc = res.tempFilePath;
uni.hideLoading();
},
fail: (err) => {
console.log('downloadFile fail, err is:', err)
}
})
}
}
}
</script>
<style>
.img {
width: 500upx;
height: 500upx;
margin: 0 95upx;
}
</style>
4:运行,跨域问题解决,图片就可以显示了