Cannot import data from csv file in d3 - javascript

I'm just learning d3, and I'm attempting to import data from a CSV file, but I keep getting the error "XMLHttpRequest cannot load file:///Users/Laura/Desktop/SampleECG.csv. Cross origin requests are only supported for HTTP. ". I've searched for how to fix this error and have ran it on a local web server, but I haven't found a solution that works for d3.v2.js. Here's a sample of the code:
var Time = []
ECG1 = []
d3.csv("/Desktop/d3Project/Sample.csv", function(data)
{
Time = data.map(function(d) {return [+d["Time"]];});
ECG1 = data.map(function(d) {return [+d["ECG1"]];});
console.log(Time)
console.log(ECG1)
});
Any help will be much appreciated.

This confused me too (I am also a d3 beginner).
So, for some reason, web browsers are not happy about you loading local data, probably for security reasons or something. Anyways, to get around this, you have to run a local web server. This is easy.
In your terminal, after cd-ing to your website's document root (thanks #daixtr), type:
python -m SimpleHTTPServer 8888 &
Okay, now as long as that terminal window is open and running, your local 8888 web server will be running.
So in my case, originally the web page I was working on was called
file://localhost/Users/hills/Desktop/website/visualizing-us-bls-data-inflation-and-prices.html
When I opened it in chrome. To open up my page on my local web server, I just typed (into the chrome search bar):
http://localhost:8888/Desktop/website/visualizing-us-bls-data-inflation-and-prices.html
Now, reading in CSVs should work. Weird, I know.

To those using built-in python webserver and who are still experiencing issues, do REMEMBER and make sure that you run the "python -m SimpleHTTPServer 8888" invocation at the correct path of which you consider to be your DocumentRoot. That is, you cannot just run 'python -m SimpleHTTPServer 8888' anywhere. You have to actually 'cd /to/correct/path/' containing your index.html or data.tsv and then from there run 'python -m SimpleHTTPServer 8888'.

Also, just learning D3 for school work. I was trying to run this simple D3 example:
https://gist.github.com/d3noob/b3ff6ae1c120eea654b5
I had the same problem as OP re: loading data using Chrome browser. I bet the great solution Hillary Sanders posted above was re: Python 2.X.
My answer is re: Python 3.X [OS: Ubuntu 16x]:
Open a terminal window within the root directory of your project, then run:
python3 -m http.server
It will serve HTTP on port 8000 by default unless it is already taken, in that case to open another port, e.g. 7800, run:
python3 -m http.server 7800
Then, on your Chrome browser address bar type:
localhost:8000
The above worked for me because I only had an index.html page in my root folder. In case, you have a HTML page with a different name, type the whole path to that local HTML page and it should work also. And, you should be able to see the graph created from the data set in my link (that must be in a folder like data/data.csv). I hope this helps. :-)

Use Firefox, idk what Chrome tries to accomplish

Related

CORS policy error on file in same folder as HTML [duplicate]

I am getting the following error:
XMLHttpRequest cannot load file:///C:/Users/richa.agiwal/Desktop/get/rm_Library/templates/template_viewSettings.html. Cross origin requests are only supported for HTTP.
I realize that this question has been answered before, but I still have not found a solution to my problem. I tried running chrome.exe --allow-file-access-from-files from the command prompt, and moved the file to the local file system, but I still get the same error.
I appreciate any suggestions!
If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.
Here are some options that I use.
Test your web page locally on Firefox, then deploy to your host.
or: Run a local server
Test on Firefox, Deploy to Host
Firefox currently allows Cross Origin Requests from files served from your hard drive
Your web hosting site will allow requests to files in folders as configured by the manifest file
Run a Local Server
Run a server on your computer, like Apache or Python
Python isn't a server, but it will run a simple server
Run a Local Server with Python
Get your IP address:
On Windows: Open up the 'Command Prompt'. All Programs, Accessories, Command Prompt
I always run the Command Prompt as Administrator. Right click the Command Prompt menu item and look for Run As Administrator
Type the command: ipconfig and hit Enter.
Look for: IPv4 Address . . . . . . . . 12.123.123.00
There are websites that will also display your IP address
If you don't have Python, download and install it.
Using the 'Command Prompt' you must go to the folder where the files are that you want to serve as a webpage.
If you need to get back to the C:\ Root directory - type cd/
type cd Drive:\Folder\Folder\etc to get to the folder where your .Html file is (or php, etc)
Check the path. type: path at the command prompt. You must see the path to the folder where python is located. For example, if python is in C:\Python27, then you must see that address in the paths that are listed.
If the path to the Python directory is not in the path, you must set the path. type: help path and hit Enter. You will see help for path.
Type something like: path c:\python27 %path%
%path% keeps all your current paths. You don't want to wipe out all your current paths, just add a new path.
Create the new path FROM the folder where you want to serve the files.
Start the Python Server: Type: python -m SimpleHTTPServer port Where 'port' is the number of the port you want, for example python -m SimpleHTTPServer 1337
If you leave the port empty, it defaults to port 8000
If the Python server starts successfully, you will see a msg.
Run You Web Application Locally
Open a browser
In the address line type: http://your IP address:port
http://xxx.xxx.x.x:1337 or http://xx.xxx.xxx.xx:8000 for the default
If the server is working, you will see a list of your files in the browser
Click the file you want to serve, and it should display.
More advanced solutions
Install a code editor, web server, and other services that are integrated.
You can install Apache, PHP, Python, SQL, Debuggers etc. all separately on your machine, and then spend lots of time trying to figure out how to make them all work together, or look for a solution that combines all those things.
I like using XAMPP with NetBeans IDE. You can also install WAMP which provides a User Interface for managing and integrating Apache and other services.
Simple Solution
If you are working with pure html/js/css files.
Install this small server(link) app in chrome. Open the app and point the file location to your project directory.
Goto the url shown in the app.
Edit: Smarter solution using Gulp
Step 1: To install Gulp. Run following command in your terminal.
npm install gulp-cli -g
npm install gulp -D
Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.
var gulp = require('gulp');
var bs = require('browser-sync').create();
gulp.task('serve', [], () => {
bs.init({
server: {
baseDir: "./",
},
port: 5000,
reloadOnRestart: true,
browser: "google chrome"
});
gulp.watch('./**/*', ['', bs.reload]);
});
Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command
npm install browser-sync gulp --save-dev
Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command
gulp serve
To add to Alan Wells's elaborate answer here is a quick fix
Run a Local Server
you can serve any folder in your computer with Serve
First, navigate using the command line into the folder you'd like to serve.
Then
npx i -g serve
serve
or if you'd like to test Serve without downloading it
npx serve
and that's it! You can view your files at http://localhost:5000
If you are using vscode, you can easily start a liver server. Click liver server at the bottom of the page, once the server is started, vscode will tell the port the project is running. Do ensure your project folder is the workspace
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).
I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:
localhost//myAPIProject
Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.
http://localhost//myAPIProject
Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

Serving locally a webapp

I'm developing an html web page which will visualize data. The intention is that this web page works only on one computer, so I don't want it to be online. Just off line. The web uses only Js, css and html. It is very simple and is not using any database, the data is loaded through D3js XMLHttpRequest. Up to now it is working with a local python server for development, through python -m SimpleHTTPServer. Eventually I will want to launch it easyer. Is it possible to pack the whole thing in a launchable app? Do you recommend some tools to do it or some things to read? What about the server part? Is it possible to launch a "SimpleHTTPServer" kind of thing without the console? Or maybe just one command which launches the server plus the web?
Thanks in advance.
Update
Save and compile following file in your folder.Double click on .pyc file to run it.
import SocketServer
import SimpleHTTPServer
import webbrowser
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
webbrowser.open(<yourip:PORT>)
This should work on all platforms
Put the following into a text file and save it with extension .bat
cd yourfolder
python -m SimpleHTTPServer port
C:\>"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "yourip:port" --new-window
This should work fine in windows
For Mac
cd yourfolder
python -m SimpleHTTPServer port
open -a "Google Chrome" --args --kiosk http://google.com
and save with extension .command
Not too sure what you are trying to achieve from reading the question. but from what i understand is that you'd like to be able to launch your application and serve it on the web when done.
you could use heroku!(www.heroku.com), same way you are hosting the application on your local, you simply make a Procfile, and in that file you put in the command that you'd normally run on your local, and push to Heroku.

D3.js: Treemap doesn't load from JSON file

I am trying to run this very example of a treemap on localhost, but I can't load the JSON file (which, by the way, is the same JSON file that the example uses).
The console returns the next error in Google Chrome:
XMLHttpRequest cannot load file:///C:/Users/Usuario/Downloads/d3/flare.json. Cross origin requests are only supported for HTTP.
The JSON file is in the same folder as the html file.
Thanks in advance for your help.
You cannot load local files because of the security policy. To quote the D3 website:
When developing locally, note that your browser may enforce strict permissions for reading files out of the local file system. If you use d3.xhr locally (including d3.json et al.), you must have a local web server. For example, you can run Python's built-in server:
python -m SimpleHTTPServer 8888 &
or for Python 3+
python -m http.server 8888 &
Once this is running, go to http://127.0.0.1:8888/.
If people working d3.js on the xampp or wamp they can run their html file as like php file by starting the server.
I found the same issue then I started the wampp server then the file get loaded successfully without any issue like "XmlHttpRequest Access control allow orgin".
I am working in WAMP. I hope same thing for XAMPP, but I am not sure...

D3 samples in a Microsoft Stack

We're trying to get familiar with D3 (http://d3js.org/), in particular samples such as http://bl.ocks.org/mbostock/3306362 and http://bl.ocks.org/mbostock/2206590. It seems all these samples use local file IO to load geolocation info. The following code snippets are common:
queue()
.defer(d3.json, "/mbostock/raw/4090846/us.json")
.defer(d3.tsv, "unemployment.tsv")
.await(ready)
while other samples often use this signature to load data:
d3.json("someJSONFile.json", function(error, uk) {
console.log(uk);
});
We've created several local html files to test out the samples, but we're running into security issues. It's apparent the script is accessing a local file, which is really giving us problems in a Microsoft stack (Apple or Linux isn't an option at this time, though we have tried Chrome, with no success). How can we enable the html file or refactor the script to have access to the local files?
You need to host the files through a web server since web browsers restrict what types of files can be accessed locally. The simplest way to do this on a windows machine:
Install python
Navigate to the directory holding your example with cmd.exe. Holding down shift, right clicking on the folder with the example and selecting Open Command Window Here is the easiest way to do this.
On the command prompt, enter python -m SimpleHTTPServer 8000, or python -m http.server 8000, on newer versions to start a web server.
Open a web browser (I would really suggest chrome, the dev tools are way ahead of ff and ie), go to 127.0.0.1:8000. The example should show up.

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