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

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

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. // 指定允许其他域名访问
  2. header("Access-Control-Allow-Origin:*");
  3. // 响应类型
  4. header("Access-Control-Allow-Methods:POST");
  5. // 响应头设置
  6. header("Access-Control-Allow-Headers:x-requested-with,content-type");
  7. 添加完毕,好了错没了,可发现数据好像有问题啊。我访问的是自己的接口,因为是以前的老接口,不能改所以只有硬着头皮改前台了

3.以前的请求参数为form data怎么这次请求神奇的变为request payload,崩溃中,最后找到要添加Content-Type:application/x-www-form-urlencoded

  1. headers: {
  2. 'Content-Type': 'application/x-www-form-urlencoded'
  3. }
  4. this.$http.post('/login/index.php?user&q=action/login', {'a': 'test', 'b': '123456'}), {
  5. headers: {
  6. 'Content-Type': 'application/x-www-form-urlencoded'
  7. }
  8. })
  9. .then(function (response) {
  10. console.log(response)
  11. })
  12. .catch(function (error) {
  13. console.log(error)
  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. 下面三种技能,我用了一种,轻松搞定。

  1. Using application/x-www-form-urlencoded format
  2. 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.
  3. **Browser**
  4. In a browser, you can use the URLSearchParams API as follows:
  5. var params = new URLSearchParams();
  6. params.append('param1', 'value1');
  7. params.append('param2', 'value2');
  8. axios.post('/foo', params);
  9. Note that URLSearchParams is not supported by all browsers, but there is a polyfill available (make sure to polyfill the global environment).
  10. Alternatively, you can encode data using the qs library:
  11. var qs = require('qs');
  12. axios.post('/foo', qs.stringify({ 'bar': 123 }));
  13. Node.js
  14. In node.js, you can use the querystring module as follows:
  15. var querystring = require('querystring');
  16. axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
  17. You can also use the qs library.
  18. 如果到这还没解决你的问题,不好意思,go for it 哈哈哈