自由屋推书网—热门的小说推荐平台!

你的位置: 首页 > 其他程序

解决Vue中调接口时出现的跨域问题

2022-04-24 10:43:46

在 vue.config.js文件中新增以下属性

module.exports = {
    devServer: {
        //跨域
        proxy: {
            '/api': {
                target: 'http://v.juhe.cn/', //你要调用的接口
                changOrigin: true,//准许跨域
                //路径重写
                pathRewrite: {
//重写路径,当我们在浏览器中看到请求的地址为:
//http://localhost:8080/api/frontend/experts/getlist 时
//实际上访问的地址是:
//http://localhost:8081/dong-guan-project/tp6-dgjx/public/index.php/frontend/experts/getlist
//因为重写了 /api
                    '^/api': '' //路径转发代理
                }
            }
        }
    }
}

然后在你要用的组件中调用(记着项目要重新启动)

  getnews() {
      axios
         .get("api/toutiao/index?type=top&key=44db60d93b75588e522684d351327b7b")
         .then((d) => {
           console.log(d);
         });
     },

这种方式只适用于项目在开发阶段设置。

Vue

编辑推荐

热门小说