克服旧API的CORB限制?

时间:2018-12-02 14:42:46

标签: javascript xml cors transit

尝试从此处的NJTransit API卸载一些更新的总线位置-http://mybusnow.njtransit.com/bustime/map/getRoutePoints.jsp?route=87-返回非常简单的XML。据我所知,没有CORS标头/策略,因此Chrome抛出错误并使用指向this issue tracker的指针来阻止请求。

route='87';

function logResult(result) {
  console.log(result);
}

function logError(error) {
  console.log('Looks like there was a problem: \n', error);
}

function validateResponse(response) {
  if (!response.ok) {
    throw Error(response.statusText);
  }
  return response;
}

function readResponseAsXML(response) {
  let responseDoc = new DOMParser().parseFromString(response, 'application/xml');
  var oSerializer = new XMLSerializer();
  var buses_xml = oSerializer.serializeToString(responseDoc);
  return buses_xml;
}

function fetchXML(pathToResource) {
  fetch(pathToResource, {mode:'no-cors'}) // 1
  .then(validateResponse) // 2
  .then(readResponseAsXML) // 3
  .then(logResult) // 4
  .catch(logError);
}

fetchXML('http://mybusnow.njtransit.com/bustime/map/getRoutePoints.jsp?route='+ route);

有什么办法解决吗?我知道这是一个基于浏览器的问题,我可以从服务器发出呼叫,一切都很好,但这正是我要摆脱的目标。当前的解决方案是从服务器获取这些更新,并通过我自己的服务器API将其传递给客户端。我想成为中间人,让客户自己获取更新的职位。

获取数据源(NJT)对其API设置进行任何更改的可能性非常低。

谢谢

1 个答案:

答案 0 :(得分:0)

请检查以下内容:

route='87';

function logResult(result) {
  console.log(result);
}

function logError(error) {
  console.log('Looks like there was a problem: \n', error);
}

function validateResponse(response) {
  if (!response.ok) {
    throw Error(response.statusText);
  }
  return response;
}

function readResponseAsXML(response) {
  let responseDoc = new DOMParser().parseFromString(response, 'application/xml');
  var oSerializer = new XMLSerializer();
  var buses_xml = oSerializer.serializeToString(responseDoc);
  return buses_xml;
}

function fetchXML(pathToResource) {
  fetch(pathToResource, {}) // 1
    .then(validateResponse) // 2
    .then(readResponseAsXML) // 3
    .then(logResult) // 4
    .catch(logError);
}

fetchXML('https://cors-anywhere.herokuapp.com/http://mybusnow.njtransit.com/bustime/map/getRoutePoints.jsp?route='+ route);

我已更改您的代码以使用CORS代理。

请检查@ CodePen: https://codepen.io/animatedcreativity/pen/b5796c4b3711b6f8d6437beff0c2c40a

示例XML响应:

<route>
        <id>87</id> 
        <rtpiFeedName></rtpiFeedName>
        <sn>87</sn> 
        <nm>87 Jersey City - Hoboken</nm> 
        <displayDesignator>87</displayDesignator> 
        <vmode>1</vmode>   

        <sbs>



        </sbs>

        <c>#ff0033</c>

        <pas>


            <pa>
                <id>3393</id>

                <d>Hoboken</d> 
                <dd>Hoboken</dd>  
                <directionRtpiFeedName></directionRtpiFeedName>

                <pt>
                    <lat>40.692060000000545</lat>
                    <lon>-74.0966800000009</lon>
                    <dtr>false</dtr> 

                    <bs>
                        <id>21028</id>
...