当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue使用axios插件请求访问API遇到的跨域问题。

vue使用axios插件请求访问API遇到的跨域问题。

2020年07月27日  | 移动技术网IT编程  | 我要评论

API地址:

http://www.caiji.me/api/test (本地开发的接口地址,访问接口会返回字符串“接口测试”;

axios请求方法:引入组件 axios后,编写请求接口方法:

mounted() {
    axios.get('http://www.caiji.me/api').then(function (res) {
        console.log(res);
    });
}

本地  运行项目时,在执行到请求时报错显示:

Access to XMLHttpRequest at 'http://www.caiji.me/api' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

很明显,属于跨域问题。此处不探讨其他解决方案。

下面说一下自己的解决方案。

本人初学vue脚手架版本为4.4.6 ,在vue.config.js 添加如下标红代码:

module.exports = {
  outputDir: '../public'
  , devServer: {
    proxy: {
      '/api': {
        target: 'http://www.caiji.me',
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api':  '/api',
        }
      }
    }
  }
}

同时将vue中请求修改为:

axios.get('/api/test').then(function (res) {
    console.log(res);
});

修改完成后,重新运行一下项目。即可完成跨域请求操作。

请求结果如下:

本文地址:https://blog.csdn.net/qq_32257643/article/details/107578404

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网