账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    localhost用Axios请求内网数据跨域问题
    28
    0

    本地用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是什么,我现在就想点一个按钮出来所有的数据,请大神指导!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 愛戀ヾ最傷人 普通会员 1楼

      在使用 Axios 跨域请求内网数据时,可以采取以下方法解决跨域问题:

      1. JSONP(JSON with Padding):JSONP 通过在请求体中包含一个查询参数(callback)来实现跨域请求。但是这种方法有一个缺点,即服务器端需要处理额外的 JSONP 参数,而且在前端页面中需要将请求头设置为 "Access-Control-Allow-Origin" 为 "*"。

      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(); }

      1. CORS(Cross-Origin Resource Sharing):在浏览器的设置中,可以允许不同源的请求。这种方法需要服务器端设置允许跨域的策略。

      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(); };

      1. 使用代理:通过将请求代理到服务器端,可以绕过服务器端的代理设置。但是这种方法需要服务器端处理额外的请求,而且在前端页面中需要将请求头设置为 "Access-Control-Allow-Origin" 为 "*"。

      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 跨域请求内网数据的问题。在实际使用中,可以根据需要选择合适的方案。

    更多回答
    扫一扫访问手机版