h5与微信小程序中的跨域问题
通过manifest.json里的h5配置来解决跨域问题
"h5": {
"router": {
"mode": "hash"
},
"devServer": {
"port": 8080,
"disableHostCheck": true,
"proxy": {
"/": {
"target": "http://localhost:3000",
"changeOrigin": true,
"secure": false
}
}
}
}
里面的基本内容都要有,如上述所示。在实际运用中还发现请求会返回html文件,然后搜索之后发现将端口加上,然后就解决了,返回的是后端设置的数据。
但是由于h5和微信小程序不一样,在写url请求地址是有区别的。h5里面写相对路径,微信小程序里面要写绝对路径。可以如下图所示使用预编译判断。
get() {
uni.request({
// h5 请求路径不能写全路径 不然即使配置了跨域,浏览器还是会显示跨域
// #ifdef H5
url: '/users/getlunbo',
// #endif
// #ifndef H5
url: 'http://localhost:3000/users/getlunbo', // 非H5端即微信小程序或App
// #endif
success: (res) => {
console.log('请求回来的数据', res);
}
})
}