TypechoJoeTheme

Dcr163的博客

uniapp H5本地开发支持跨域请求

2021-05-22
/
0 评论
/
98 阅读
/
正在检测是否收录...
05/22

uniapp H5本地开发支持跨域请求

使用uniapp本地开发的时候,在浏览器端调试效果的话,可能需要请求其他域名的接口,普通网络请求访问,可能会提示下面的跨域错误:
Access to XMLHttpRequest at 'http://www.dcr163.cn/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

解决的办法

也很简单,在uniapp项目根目录找到mainfest.json配置文件,找到H5的配置信息,如果没有H5的配置信息,则自己新增配置信息:

    "h5": {
        "title": "朋友圈说说【凡人阁】",
        "devServer": {
            "port": 8080,
            "disableHostCheck": true,
            "proxy": {
                "/dcr163": {
                    "target": "https://www.dcr163.cn",
                    "changeOrigin": true,
                    "secure": false,
                    "pathRewrite": {
                        "^/dcr163": "" //匹配请求路径里面有 /api 替换成 https://www.xxx.cn
                    }
                }
            },
            "https": false
        }
    }

网络请求

把原来的请求地址修改一下

uni.request({
    url: 'https://www.dcr163.cn/api.php',
    data: data,
    method: 'GET',
    header: {'content-type':'application/json'},
    success: (res) => {
        successFun && successFun(res);
    },
    fail: (error) => {
        failFun && failFun(error);
    },
    complete: (res) => {
        completeFun && completeFun(res)
    }
})
更新为
uni.request({
    url: '/dcr163/api.php',
    data: data,
    method: 'GET',
    header: {'content-type':'application/json'},
    success: (res) => {
        successFun && successFun(res);
    },
    fail: (error) => {
        failFun && failFun(error);
    },
    complete: (res) => {
        completeFun && completeFun(res)
    }
})
赞(0)
版权属于:

Dcr163的博客

本文链接:

https://dcr163.cn/466.html(转载时请注明本文出处及文章链接)

评论 (0)