Fetching in javascript with absolute url and relative url

China☆狼群 提交于 2019-12-11 07:34:12

问题


I have a script that I run on my local server and that fetches a php file (on the local server too). If I write the url to fetch as a relative path, I get the file without problems, but, if I add the 127.0.0.1/mypath/myFile, I get a 403 error.

function localServerCall() {
    var urlLocalServer = '127.0.0.1:8000/mypath/myfile.php';
    //var urlLocalServer = 'myfile.php';   //THIS WORKS!
    fetch(urlLocalServer).then(function(response) {
      console.log(response.json);
      return response.json();
  }).then(function(data) {
      console.log(data)
  }).catch(function(err) {
      console.log ('ERROR LOCALSERVER', err);
  })
}

I was wondering if there are some limitations on the use of absolute/relative urls with fetch or if this problem might be due to something else.


回答1:


A URL that doesn't start with a scheme or with // is treated as a path (part of a relative URL).

From http://example.com/foo/, your URL resolves to http://example.com/foo/127.0.0.1:8000/mypath/myfile.php.

You almost certainly want:

var urlLocalServer = 'http://127.0.0.1:8000/mypath/myfile.php';


来源:https://stackoverflow.com/questions/37725659/fetching-in-javascript-with-absolute-url-and-relative-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!