1. 程式人生 > >Vue.js裡面使用Axios傳送Post請求出現跨域

Vue.js裡面使用Axios傳送Post請求出現跨域

在Vue.js裡面使用Axios傳送POST請求出現以前跨域的形式:


具體報錯如:Failed to load http://192.168.33.10:8009/api/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

比較納悶: 因為我後端PHP程式碼裡面已經設定了允許跨域:

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods:POST, GET, OPTIONS');

不明白為什麼還是出現跨域?同時這裡需要提醒的是: 如果你要進行身份認證的話,header裡面

Access-Control-Allow-Origin 不可以設定為 * ,這個是以前踩過的坑,你可以填寫為你允許跨域的ip地址或者域名

在網上查了半天,很多人使用qs解決了這個問題,現在我還是不明白什麼使用qs會解決這個問題。還有人說是Axios的問題,它

在傳送資料時需要字串的方式進行傳送。在Axios的GitHub上面看到:

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:

const params = new URLSearchParams
(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

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

Or in another way (ES6),

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

我在專案中也使用了qs,然後就解決了這個跨域的問題.

首先在npm中安裝:

npm install qs

然後再專案中引入 import qs from 'qs'

然後我們傳送Axios的時候就可以使用qs.stringify了

 axios.post('http://192.168.33.10:8009/api/token', 
       qs.stringify({
        email: email,
        password: pass,
      }))
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);

      });

我是這樣寫的就可以傳送了

參考文章: