vue2.0下axios实现跨域踩的坑

按踩坑顺序叙述。本人对http了解太少,所以坑踩得较多。 
1.开始进行跨域时,知道vue2.0官方推荐axios进行ajax请求,大致看一下https://www.npmjs.com/package/axios axios的用法,感觉挺好理解嘛,封装的挺好,用时发现,不对啊。跨域设置在哪?最后找到了它

proxyTable: {
   '/shopping':{//此处并非一定和url一致。
      target:'https://mainsite-restapi.ele.me/shopping',
      changeOrigin:true,//允许跨域
      pathRewrite:{
        '^/shopping': ''
      }
    }
}
此段代码表示,如果请求地址以/login开头,则自动加上target。
如:/shopping/v2/restaurant/category  等于
https://mainsite-restapi.ele.me/shopping/v2/restaurant/category
设置成功,感觉axios就是方便。走着走着发现。。。不对
1
2
3
4
5
6
7
8
9
10
11
12
13
2.get请求成功,换成post请求。坑爹啊

:8000/#/login:1 XMLHttpRequest cannot load http://cunguan.com/index.php?user&q=action/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
1
查了半天发现直接访问接口时,要对后端响应头进行设置(最后发现如果用1中的方法进行跨域访问设置则不需要在后端添加响应头)
1
// 指定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 响应类型
header("Access-Control-Allow-Methods:POST");
// 响应头设置
header("Access-Control-Allow-Headers:x-requested-with,content-type");
添加完毕,好了错没了,可发现数据好像有问题啊。我访问的是自己的接口,因为是以前的老接口,不能改所以只有硬着头皮改前台了
1
2
3
4
5
6
7
3.以前的请求参数为form data怎么这次请求神奇的变为request payload,崩溃中,最后找到要添加Content-Type:application/x-www-form-urlencoded

headers: {
     'Content-Type': 'application/x-www-form-urlencoded'
}
this.$http.post('/login/index.php?user&q=action/login', {'a': 'test', 'b': '123456'}), {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
})
    .then(function (response) {
       console.log(response)
     })
     .catch(function (error) {
       console.log(error)
     })
好吧  请求默认的需要修改我认了,改过之后发现。。。我参数呢?这次好了,参数都丢了继续查文档吧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4.Content-Type:application/x-www-form-urlencoded 时参数格式的问题下面摘自 
https://github.com/mzabriskie/axios/blob/master/README.md#using-applicationx-www-form-urlencoded-format. 下面三种技能,我用了一种,轻松搞定。

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

**Browser**

In a browser, you can use the URLSearchParams API as follows:

    var params = new URLSearchParams();
    params.append('param1', 'value1');
    params.append('param2', 'value2');
    axios.post('/foo', params);
Note that URLSearchParams is not supported by all browsers, but there is a polyfill available (make sure to polyfill the global environment).
Alternatively, you can encode data using the qs library:

    var qs = require('qs');
    axios.post('/foo', qs.stringify({ 'bar': 123 }));

Node.js

In node.js, you can use the querystring module as follows:

    var querystring = require('querystring');
    axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

You can also use the qs library.
原文:https://blog.csdn.net/z852064121/article/details/75460408?utm_source=copy 
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue项目中使用axios发起跨域请求存在以下几种解决方案: 1. 通过设置proxyTable代理解决跨域 在`config/index.js`中可以找到`dev`下的`proxyTable`属性,可以设置代理规则,如下所示: ``` module.exports = { dev: { // ... proxyTable: { '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '/mock' // 将/api替换为/mock } } } } } ``` 上面的代码中,代理规则中的`/api`表示需要代理的请求路径,`target`表示代理目标地址,`changeOrigin`表示是否改变请求头中的origin字段,`pathRewrite`表示路径重写规则。 2. 在服务器端设置CORS(跨域资源共享)策略 在服务器端设置CORS策略,允许指定的域名或IP地址访问API。具体的设置方法可以参考服务器框架的文档,比如,如果是使用Express框架,可以通过以下代码启用CORS: ``` const express = require('express') const app = express() app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'http://localhost:8080') // 允许访问的域名或IP地址 res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') // 允许的请求方法 res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization') // 允许的请求头 res.header('Access-Control-Allow-Credentials', 'true') // 是否允许发送Cookie next() }) // 其他路由和中间件 ``` 3. 使用JSONP解决跨域 JSONP是一种跨域请求方式,只支持GET请求,但是需要服务器端支持。在Vue中可以使用vue-jsonp插件来实现JSONP请求,具体使用方法可以参考插件文档。 以上三种方法都可以解决Vue项目中使用axios发起跨域请求的问题,选择哪种方法取决于具体的应用场景和服务器端环境。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值