Reputation: 5016
I have following directory structure of my project.
I have following code in my index.js
file for loading website.json
file.
index.js
componentDidMount() {
$.ajax({
url: "../website.json",
type: "GET",
dataType: 'json',
ContentType: 'application/json',
success: function(data) {
this.setState({data: data});
console.log(data);
}.bind(this),
error: function(jqXHR) {
console.log(jqXHR);
}.bind(this)
})
}
The problem is that I am using npm start
command to server my react app from local directory of my application. This serves my app at http://localhost:3000/
. Now the problem is that the application tries to load the website.json
file from http://localhost:3000/website.json
which gives a 404 not found
error.
So, my question is how my website.json
file can be loaded from my project directory instead of localhost.
Note: my project folder is not at localhost but at virtual host.
Update: I am specifically asking why the ajax call is unable to load data from my project folder (I am using relative addressing) and instead including path from localhost. I want to load data using ajax call is it possible or not.
Upvotes: 0
Views: 3144
Reputation: 317
Your webserver (I would guess Express) will be serving files from the 'public' folder.
For security reasons, web servers do not allow access to files outside of the directory root (/public in your case), so you will not be able to get the file by ajax (or from the browser).
If you really want to, you could either:
Upvotes: 2
Reputation: 2751
You may include it inside source as
var website = require('../website.json');
So it will be embedded during compile time.
Another way to do it - move website.json
to public folder, than you may access it as ajax('/website.json'...
Upvotes: 2
Reputation: 2327
I assume you are using ES6
/ES2015
since you are using react
. So instead of doing it in componentDidMount
you can just add this at the top:
import websiteData from '../website.json';
And then you can just use websiteData
as a variable in your component.
Upvotes: 0