vue2.0下axios實現跨域踩的坑
阿新 • • 發佈:2018-12-02
按踩坑順序敘述。本人對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. 如果到這還沒解決你的問題,不好意思,go for it 哈哈哈 --------------------- 作者:太倉一粟 來源:CSDN 原文:https://blog.csdn.net/z852064121/article/details/75460408 版權宣告:本文為博主原創文章,轉載請附上博文連結!