美文网首页
uni-app及vue浏览器跨域问题解决

uni-app及vue浏览器跨域问题解决

作者: Zachary46 | 来源:发表于2022-02-17 16:39 被阅读0次

    以猫眼电影接口为例:
    假设请求接口https://m.maoyan.com/ajax/movieOnInfoList遇到跨域问题

    vue解决跨域

    在项目根目录下新建vue.config.js文件,做如下配置


    image.png
    module.exports = {
        devServer: {
            proxy: {
                '/ajax': {
                    target: "https://m.maoyan.com",
                    changeOrigin: true
                }
            }
        }
    }
    

    在进行网络请求的时候请求路径不用拼接域名

    fetch("/ajax/movieOnInfoList")
           .then(res=>res.json()).then(res=>{
            console.log(res)
          })
    

    '/ajax'匹配到路径会自动在前面加入target配置的域名https://m.maoyan.com

    uni-app解决跨域

    在mainifest.json的源码视图里添加如下代码:


    image.png
     "h5" : {
            "devServer" : {
                "proxy": {
                    "/ajax":{
                        "target": "https://m.maoyan.com",
                        "changeOrigin": true
                    }
                }
            }
        }
    

    代码和vue配置差不多,唯一区别就是键值对要加""

    相关文章

      网友评论

          本文标题:uni-app及vue浏览器跨域问题解决

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