Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't load js file in my local apache2 server?

Tags:

In my local domain's webpage , both
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
jq.src = http://127.0.0.1/js/jquery-3.3.1.min.js
can be loaded.

In the stackoverflow's webpage,right click to enter into chrome's inspect--console.

const jq = document.createElement('script');
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
document.head.appendChild(jq);
jq.addEventListener('load', () => {
  console.log("hello world");
  console.log($ === jQuery);
});

The remote jquery.js file can be loaded,now to replace it with local js file--http://127.0.0.1/js/jquery-3.3.1.min.js .
Why can't load the js file in my local apache2?

enter image description here

like image 450
showkey Avatar asked Aug 21 '18 07:08

showkey


1 Answers

Sites you are visiting can apply security policy for javascript - which includes the debugger. I think what you are seeing is the application of the content security policy associated with the web page you are visiting.

You can see this in the page headers. In Chrome (as explained here), you can view the html headers sent with the page:

Open the developer panel, select the "network" tab, and reload the page.

For stackoverflow, look under the "name" column for "stackoverflow.com" - there may be two if you originally loaded it via http, so find the one which is https - probably the second one. Click that one, and select the "headers" tab on the right. You will see in amongst the response headers:

content-security-policy: upgrade-insecure-requests

This is explained here.

Basically, it tells the browser that all http requests should be "upgraded" to https. So when you try to access http://127.0.0.1/..., your browser upgrades the request to https://127.0.0.1/..., which your local server probably isn't set up to handle.

This is not limited to Chrome - all modern browsers should do this.

I browsed, for example, a few sites with Safari, and, in some cases, got an error message, such as on GitHub:

Refused to load https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js because
it does not appear in the script-src directive of the Content Security Policy.

That is another variety of content security policies you can read about here.

like image 180
wordragon Avatar answered Oct 11 '22 14:10

wordragon