本地用vue已经建好了,现在需要读数据,公司后台给了一个接口文档,没怎么看懂。
我现在本机是localhost,有公司服务器内网地址,请求时出了2个错:
1.OPTIONS http://xxx.xxx.xxx.xxx:9005/api/FlightInfo/FlightInfoSearch 405 (Method Not Allowed)
2.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. The response had HTTP status code 405.
我的axios配置有baseURL、timeout和headers'Content-Type' : 'application/x-www-form-urlencoded'
搜了资料,解决方法一是:“后台设置:'Access-Control-Allow-Origin':'*'
”;
方法二是:
import axios from 'axios';
import qs from 'qs';
axios.post('http://www.xyz.com/request', qs.stringify(params))
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
但是我确实不知道params是什么,我现在就想点一个按钮出来所有的数据,请大神指导!
在使用 Axios 跨域请求内网数据时,可以采取以下方法解决跨域问题:
javascript
// 通过在请求体中包含一个查询参数来实现跨域请求
function getServerSideData(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
}
javascript
// 在服务器端设置允许跨域的策略
window.xmlHttpRequest = function(options) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/data", true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
};
javascript
// 使用代理
function getServerSideData(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
}
以上方法都可以解决使用 Axios 跨域请求内网数据的问题。在实际使用中,可以根据需要选择合适的方案。