美文网首页
Taro - 本地H5无法访问远程服务器(跨域问题)

Taro - 本地H5无法访问远程服务器(跨域问题)

作者: 汗青fullstack | 来源:发表于2020-05-30 15:48 被阅读0次
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) {
     
    }
  })

相关文章

网友评论

      本文标题:Taro - 本地H5无法访问远程服务器(跨域问题)

      本文链接:https://www.haomeiwen.com/subject/oljqahtx.html