Reputation: 75
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
Reputation: 36311
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
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