3

Im fairly new to node.js and express. My question is how to correctly retrieve json data in a client side javascript file since im getting a 404 code about the .json file not being found.

my file structure is a generic express structure and the .json file is in the nodeapp folder right below the package.json file and app.js. Im trying to access this file from a javascript file that is saved in public/javascripts folder but can seem to get around it. here is the function im trying to implement in the .js file:

function getJSONData(){
    var json;
    $.getJSON('/public/web_text.json', function(data){

        json = data
    });
} 

1 Answer 1

4

Option 1

You need to setup static files in express, and you do it like this:

app.use(express.static(__dirname + '/public'))

You then can call it from your client (without the public prefix):

$.getJSON('/javascript/web_text.json', function(data){});

https://expressjs.com/en/starter/static-files.html


Option 2

Your other option is to send it via sendFile http://expressjs.com/en/api.html#res.sendFile:

app.get('/public/web_text.json', (req, res) => {
    res.sendFile(__dirname + '/my_json_file.json');
});

Then in your client you can call it like this:

$.getJSON('/public/web_text.json', function(data){})
Sign up to request clarification or add additional context in comments.

5 Comments

still same error.... my web_text.json file is not saved under the public/javascripts file! it is saved in the main app folder where the package.json and app.js is located
when i reload the browser and call the function in the client side js file i get an error saying that the variable app was not defined...
that is your server side code, it needs to go there
so you're saying option 2 code must go in my app.js file?
option 1 and/or option 2 must go in your app.js file, aka the file loaded via node

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.