0

I am building an application where I need to pull data from a local JSON file in my app, parse it, and generate content on my application using this data. I already read online that due to cross origin request issues, I need to host my app on a server. I have already set it up on a working local Node server. My question now really, is how do I proceed? I don't have a lot of experience making XMLhttp requests, do I just pass my request the file path to the local JSON file? I would like the callback function just to console log some of the data at first, just so I know that it's working. Also, I want to try this out first using just plain javascript, no libraries or frameworks (I used Express, but just for the server), any help or nudge in the right direction would be greatly appreciated. Thanks!

2 Answers 2

1
var x = new XMLHttpRequest();
x.open('/file.json');
x.onreadystatechange = function(){
    if(x.readyState == 4){
        callback(x.responseText);
    }
};
x.send();

function callback(resp){
    console.log(resp);
}

here you still need to do more stuff for cross-browser

Hope this helps you :)

Sign up to request clarification or add additional context in comments.

1 Comment

Just to be clear, this would be the code in my javascript file that makes the request. But there would still need to be code in my server.js file that handles the response right? An example being : app.get('/file.json',function(req,res){ res.send('file.json'); });
1

Making XMLhttp requests from javascript is not different than requesting a web page in a browser, ie. you have to use an URL, not a file path.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.