Taro - 本地H5无法访问远程服务器(跨域问题)
我们在执行npm run dev:h5
之后,其实是在本地创建了一个localhost服务器,当我们代码中使用Taro.request()访问远端服务器接口的(比如请求地址为http://xxx.com),其实是访问报错的(见下图)

解决办法1:
npm run build:h5
编译后的dist文件夹提交至http://xxx.com
访问的目录,设置服务器为当前域名可以访问的,那么就不会报这个错误,这个为正式环境的,本地测试还是不行。
解决办法2:
通过设置代理解决本地请求远端服务器的跨域问题,在config/dev.js
做如下配置:
h5: {
devServer: {
host: 'localhost',
port: 10086,
proxy: {
'/index.php/roche': {//接口访问路径
target: 'http://xxx.com', // 服务端域名
changeOrigin: true
}
}
},
}
这样就通过代理的方式访问到了接口了。
注意:Taro.request()
中 mode: 'no-cors',
Taro.request({
url: API_BASE_URL,
data: params,
method: method,// OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
'content-type': 'application/x-www-form-urlencoded', // 默认值
},
mode: 'no-cors',
success: function (res) {
},
fail: function (res) {
}
})
网友评论