cjlogrono11
cjlogrono11

Reputation: 75

using JSON data in client side javascript file

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
    });
} 

Upvotes: 3

Views: 1117

Answers (1)

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

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){})

Upvotes: 4

Related Questions