欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【原创】Vue.js 中 axios 跨域访问错误

程序员文章站 2022-10-16 12:33:40
1、假如访问的接口地址为 http://www.test.com/apis/index.php (php api 接口)2、而开发地址为http://127.0.0.1:8080,当axios发起请求时,出现如下错误:Failed to load http://www.test.com/apis/i ......

1、假如访问的接口地址为 http://www.test.com/apis/index.php  (php api 接口)

2、而开发地址为http://127.0.0.1:8080,当axios发起请求时,出现如下错误:

failed to load http://www.test.com/apis/index.php?&act=login: the value of the 'access-control-allow-origin' headerin the response must not be the wildcard '*' when the request's credentials mode is 'include'. origin 'http://127.0.0.1:8080' is therefore not allowed access. the credentials mode of requests initiated by the xmlhttprequest is controlled by the withcredentials attribute.

解决方法:
1、修改config/index.js, 修改 proxytable

    proxytable: {
      '/apis': {
          target: 'http://www.test.com/apis/',  // 接口地址
          changeorigin: true,  
          pathrewrite: {
              '^/apis': ''   //需要rewrite重写的,
          }              
      }
    },


2、重启 npm run dev    (很重要,否则不生效)

3、访问接口(访问时通过代理转发的,有点类似apache的urlrewrite,不需要完整http://www.test.com网址。)

                this.$api.get('/apis/index.php?act=login', {
                    "act": "login"
                  }, response => {
                       //success
                  },error => {
                       //error
                  }
                );

  

 

大功告成,成功解决错误,另外:php端不需要做任何的header设置,网上很多教程胡说八道,根本不能实现跨域