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
在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地址或者域名
这个地址里面有为什么不可以设置为* 的解释 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
在网上查了半天,很多人使用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);
});
我是这样写的就可以发送了
参考文章:
https://segmentfault.com/q/1010000007665348
更多推荐
所有评论(0)