Using JSON data in client side javascript file

I'm pretty new to node.js and express. My question is how to get the json data in the javascript file correctly on the client side, since im getting a 404 code about the .json file not found.

my file structure is a generic expression structure and the .json file is in the nodeapp folder right below the package.json and app.js. I'm trying to access this file from a javascript file that is saved in a folder public/javascripts

, but it might seem like it got 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
    });
} 

      

+3


source to share


1 answer


Option 1

You need to set up static files in the expression and you do the following:

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

      

Then you 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

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

      

+3


source







All Articles