XMLHttpRequest无法加载具有安全性检查的Chrome本地主机资源

XMLHttpRequest无法加载具有安全性检查的Chrome本地主机资源

问题描述:

I have Chrome Version 49.0.2623.108 (64-bit) running on OS X 10.11.4.

From the Terminal:

I ran:

> ls /tmp
  wtf.jpg

> ps -ef | grep -i chrome | grep -v grep
  <empty line>

After quitting Chrome, just making sure no instances is still running.

Then I open Chrome with the following argument to skip cross origin check:

> open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files"

I also tried:

> open /Applications/Google\ Chrome.app/ --args --disable-web-security"

Now, I run the trivial go server:

package main

import "net/http"

func main() {
    panic(http.ListenAndServe(":8080", http.FileServer(http.Dir("/tmp"))))
}

Then finally, I point Chrome to a local html5 page in /tmp containing this script:

var req = new XMLHttpRequest();
req.open('GET', "localhost:8080/wtf.jpg");
req.onload = function() { 
  console.log("succeeded");
};
req.onerror = function() {
  Error("Network Error");
};
req.send();

To finish with this error:

XMLHttpRequest cannot load localhost:8080/wtf.jpg. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Is there a way around this annoyance?

I solved this problem by changing two things:

1) I changed the underqualified "localhost:8080/wtf.jpg" in my XMLHttpRequest.open to "http://localhost:8080/wtf.jpg". That solved the Chrome error message.

2) I updated my simplistic go server:

package main

import "net/http"

const PORT = ":8080"

func handler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "OPTIONS" {
        w.Header().Set("Access-Control-Allow-Origin", "http://localhost"+PORT)
    } else {
        http.ServeFile(w, r, "wtf.html")
    }
}

func main() {
    panic(http.ListenAndServe(PORT, http.HandlerFunc(handler)))
}

That's not safe for production but good enough for local testing.