第一次写博客,主要是记录自己的一些新的,不好的地方忘各位多多指点,请不要吐槽;
按踩坑顺序叙述。本人对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': '' } } } 此段代码表示,如果请求地址以/shopping开头,则自动加上target。 如:/shopping/v2/restaurant/category 等于 https://mainsite-restapi.ele.me/shopping/v2/restaurant/category 设置成功,感觉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中的方法进行跨域访问设置则不需要在后端添加响应头)
// 指定允许其他域名访问 header("Access-Control-Allow-Origin:*"); // 响应类型 header("Access-Control-Allow-Methods:POST"); // 响应头设置 header("Access-Control-Allow-Headers:x-requested-with,content-type"); 添加完毕,好了错没了,可发现数据好像有问题啊。我访问的是自己的接口,因为是以前的老接口,不能改所以只有硬着头皮改前台了
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) }) 好吧 请求默认的需要修改我认了,改过之后发现。。。我参数呢?这次好了,参数都丢了继续查文档吧
4.Content-Type:application/x-www-form-urlencoded 时参数格式的问题下面摘自
https://github.com/mzabriskie/axios/blob/master/README.md#using-applicationx-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. 如果到这还没解决你的问题,不好意思,go for it 哈哈哈
此方法需要引入qs这个包,用es6语法引入也可以,即import qs from 'qs';