Cross origin in JavaScript import module - javascript

I have an index.html file that connect to file called main.js.
I try to import another js file into the main.js using import, but always get the following error:
Access to script at 'file:///C:/...js/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I tried to open a server but it didn't solve the problem. I don't know if the problem is in my html file or js files and I really need your help.
My code goes like this:
index.html
<body>
<script type="module" src='./js/main.js'></script>
</body>
main.js
import {
double
} from './utils.js';
utils.js
export function double(n) {
return n * 2;
}

You've probably fixed the problem by now, but for anyone googling in the future, here's the solution.
The error message says that you can't access the file from origin "null", and states that you can only do these requests with certain protocol schemes. The protocol scheme that local files on your computer have is "file://", and I think the origin: "null" thing is about it not being on a website (e.g. http://a.com vs file://a/b/c).
What you need to do to fix this is start a local server. The easiest approach is to use this python one-liner. If you are on MacOSX or Linux, go ahead and use the below command:
$ cd path/to/website
$ python -m SimpleHTTPServer 8080
Serving HTTP on 0.0.0.0 port 8000 ...
If you are on Windows, you need to install Python before making the server. To do so, go to the downloads page on their website and download the latest version. To check if it is installed, run this in the command prompt:
python -V
If you get something like Python 3.9.5, you can go ahead and run the command mentioned before.
Once you have got the server started, just navigate to http://localhost:8080/ in your browser.

Related

Threejs Model Loading: "Access to XMLHttpRequest .. from origin 'null' has been blocked by CORS policy" - How to Test Locally? Or Simple Upload?

I'm playing around with three.js locally with a single HTML page, and I want to play around with loading and moving around 3D object files. From sample code I have the following copied:
var loader = new THREE.AMFLoader();
loader.load( './models/rook.amf', function ( amfobject ) { //'./models/rook.amf'
scene.add( amfobject );
render();
} );
And in Chrome I get the following error:
Access to XMLHttpRequest at 'file:///C:/Users/me/Desktop/project/models/rook.amf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
What's a simple and safe way I can get around this and get back to learning threejs? Can I add some sort of permission code somewhere? Upload my 3D model somewhere and load from an http location (and if so, where could I do this easily and free)?
There are two ways to solve this:
1.Change security for local files in a browser. For chrome, this can be done by searching for the path of your Chrome executable and then, on your cmd :
> "C:\PathTo\Chrome.exe" --allow-file-access-from-files
2.Run files from a local web server. This allows you to access your page as:
http://localhost/yourFile.html
You can get more information to Run a local server here
Instead of directly giving the file path, you can serve your html file with simple server: https://www.npmjs.com/package/http-server.
Open a terminal:
cd ./Users/me/Desktop/project/
npm install --global http-server
http-server -p 4200
This will serve index.html file at http://localhost:4200/ on your default browser.

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https

I'm facing this issue with chrome and IE. I have developed HTML player in that i used XML to load the data inside that player. all pages have been accessed through XML.it work fine when I use any server to load that data inside player.I use WAMP server now. But now I'm thinking about making it as an offline version and write it inside CD. but when I open my player.html file directly without having server, the XML data not going to load.it showing following error in the console.
XMLHttpRequest cannot load file:///C:/wamp/www/TTT_BR/english.xml. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
you must run your app in the server , use node js
1- Install NodeJS // Hint: If you're on a Mac, you want to install and use Homebrew for this
2- Open your favorite terminal emulator
2- Install http-server by running: npm install http-server -g
3- Start http-server by running: http-server 'path/to/your/angular/root/directory' -o
That last command — specifically, the -o flag — should open a browser window at: localhost:8080
OR// use cd to find your directory app
and use this command : http-server . -o
"." mean your current directory
you can see : https://teamtreehouse.com/community/i-am-not-able-to-load-my-json-file
for testing/development purposes, the simplest solution is to use firefox browser.
Pretty much everyone has python on mac/linux by default. Who doesent, can easily get it.
python -m SimpleHTTPServer
will give you a local server # http://localhost:8000.
From there you can access whatever file you'd like for your app.
Note: use python -m http.server for python versions 3.0+
Or you can run a web server like Apache and MySQL in XAMPP Control Panel. Put your file folder inside /htdocs inside /xampp folder and run your code in the browser using localhost.

not found using http-server node.js

I install http-server globally and still failed to load my angular app. I can start by doing http-server C:\Users\Alex\Desktop\angularjsTDD\app but when I visit localhost:8080 the terminal has a not found error message. The structure of my app can be found in githib
https://github.com/eldyvoon/angularTDD
Previously I was using express as backend but I want to try to use something simpler, but failed to get it to work.
If I visit index.html without using http-server like file:///C:/Users/Alex/Desktop/angularjs%20TDD/app/index.html I got error of Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. in chrome.
If you are trying to serve static files I think you need to place a folder called public in the directory you are serving from. Soi in your structure create a folder called public and put all of your files in there. Serving app should then load index.html from the public folder.
I was using some path starting http-server which was wrong.
I've found the solution. The correct workaround would be
cd into my project, run http-server.

xmlhttp request cannot load the file

am getting the following error please help mejavascript ,
angular.min.js:103 XMLHttpRequest cannot load file:///C:/Users/DELL/Documents/jmyangularjsprojects/myangularjsprojects/login.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.(anonymous function) # angular.min.js:103
I believe you are trying to run your application from your local file system, rather than using a web server. My first recommendation for you is to host the files on a web server.
If you are using Chrome, it won't let you do cross origin requests, you cannot load file:/// and instead you need to use http:// protocol at all times.
Use this workaround for chrome as a temporary fix.
Find the path where you installed Chrome and do
> "C:\PathTo\Chrome.exe" --allow-file-access-from-files
XMLHttpRequest can not load file means you can not parse an external data file (ex csv file). This is for security reason inside Chrome. However, to be able to download your data using d3.csv, you must follow the following steps:
Open you anaconda command window (Anaconda Prompt) (test Python is working)
Go to the directory where is your html file (cd xxx/xxx/xxx/index.html)
Run the following command: python -m http.server (in Python 3)
You will see: Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/).
Open a Chrome: http://localhost:8000
Then execute Ctrl + Shift I to open the development window, then click on Console to see your csv data.
This will solve your problem. Hope this will help.

Cross origin requests are only supported for HTTP but it's not cross-domain

I'm using this code to make an AJAX request:
$("#userBarSignup").click(function(){
$.get("C:/xampp/htdocs/webname/resources/templates/signup.php",
{/*params*/},
function(response){
$("#signup").html("TEST");
$("#signup").html(response);
},
"html");
But from the Google Chrome JavaScript console I keep receiving this error:
XMLHttpRequest cannot load
file:///C:/xampp/htdocs/webname/resources/templates/signup.php. Cross
origin requests are only supported for HTTP.
The problem is that the signup.php file is hosted on my local web server that's where all the website is run from so it's not cross-domain.
How can I solve this problem?
I've had luck starting chrome with the following switch:
--allow-file-access-from-files
On os x try (re-type the dashes if you copy paste):
open -a 'Google Chrome' --args -allow-file-access-from-files
On other *nix run (not tested)
google-chrome --allow-file-access-from-files
or on windows edit the properties of the chrome shortcut and add the switch, e.g.
C:\ ... \Application\chrome.exe --allow-file-access-from-files
to the end of the "target" path
If you’re working on a little front-end project and want to test it locally, you’d typically open it by pointing your local directory in the web browser, for instance entering file:///home/erick/mysuperproject/index.html in your URL bar. However, if your site is trying to load resources, even if they’re placed in your local directory, you might see warnings like this:
XMLHttpRequest cannot load file:///home/erick/mysuperproject/mylibrary.js. Cross origin requests are only supported for HTTP.
Chrome and other modern browsers have implemented security restrictions for Cross Origin Requests, which means that you cannot load anything through file:/// , you need to use http:// protocol at all times, even locally -due Same Origin policies. Simple as that, you’d need to mount a webserver to run your project there.
This is not the end of the world and there are many solutions out there, including the good old Apache (with VirtualHosts if you’re running several other projects), node.js with express, a Ruby server, etc. or simply modifying your browser settings.
However there’s a simpler and lightweight solution for the lazy ones. You can use Python’s SimpleHTTPServer. It comes already bundled with python so you don’t need to install or configure anything at all!
So cd to your project directory, for instance
1
cd /home/erick/mysuperproject
and then simply use
1
python -m SimpleHTTPServer
And that’s it, you’ll see this message in your terminal
1
Serving HTTP on 0.0.0.0 port 8000 ...
So now you can go back to your browser and visit http://0.0.0.0:8000 with all your directory files served there. You can configure the port and other things, just see the documentation. But this simply trick works for me when I’m in a rush to test a new library or work out a new idea.
EDIT:
In Python 3+, SimpleHTTPServer has been replaced with http.server. So In Python 3.3, for example, the following command is equivalent:
python -m http.server 8000
You need to actually run a webserver, and make the get request to a URI on that server, rather than making the get request to a file; e.g. change the line:
$.get("C:/xampp/htdocs/webname/resources/templates/signup.php",
to read something like:
$.get("http://localhost/resources/templates/signup.php",
and the initial request page needs to be made over http as well.
I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.
Install express
npm install express
Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server
Put something like the following in the server.js file and read about this on the express gihub site:
var express = require('express');
var app = express();
var path = require('path');
// __dirname will use the current path from where you run this file
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
app.listen(8000);
console.log('Listening on port 8000');
After you've saved server.js, you can run the server using:
node server.js
Go to http://localhost:8000/FILENAME and you should see the HTML file you were trying to load
If you have nodejs installed, you can download and install the server using command line:
npm install -g http-server
Change directories to the directory where you want to serve files from:
$ cd ~/projects/angular/current_project
Run the server:
$ http-server
which will produce the message Starting up http-server, serving on:
Available on:
http://your_ip:8080 and
http://127.0.0.1:8080
That allows you to use urls in your browser like
http://your_ip:8080/index.html
It works best this way. Make sure that both files are on the server. When calling the html page, make use of the web address like: http:://localhost/myhtmlfile.html, and not, C::///users/myhtmlfile.html. Make usre as well that the url passed to the json is a web address as denoted below:
$(function(){
$('#typeahead').typeahead({
source: function(query, process){
$.ajax({
url: 'http://localhost:2222/bootstrap/source.php',
type: 'POST',
data: 'query=' +query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
}
});
}
});
});
REM kill all existing instance of chrome
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
change chromeLocation path with yours.
save above as .bat file.
drag drop you file on the batch file you created. (chrome does give restore pages
option though so if you have pages open just hit restore and it will work).
You can also start a server without python using php interpreter.
E.g:
cd /your/path/to/website/root
php -S localhost:8000
This can be useful if you want an alternative to npm, as php utility comes preinstalled on some OS' (including Mac).
For all python users:
Simply go to your destination folder in the terminal.
cd projectFoder
then start HTTP server
For Python3+:
python -m http.server 8000
Serving HTTP on :: port 8000 (http://[::]:8000/) ...
go to your link: http://0.0.0.0:8000/
Enjoy :)

Categories