简体   繁体   English

在客户端javascript文件中使用JSON数据

[英]using JSON data in client side javascript file

Im fairly new to node.js and express. 我是node.js和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. 我的问题是如何正确检索客户端javascript文件中的json数据,因为我得到了关于.json文件未找到的404代码。

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. 我的文件结构是一个通用的快速结构,.json文件位于package.json文件和app.js正下方的nodeapp文件夹中。 Im trying to access this file from a javascript file that is saved in public/javascripts folder but can seem to get around it. 我试图从保存在public/javascripts文件夹中的javascript文件访问此文件,但似乎可以解决它。 here is the function im trying to implement in the .js file: 这是我试图在.js文件中实现的函数:

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

        json = data
    });
} 

Option 1 选项1

You need to setup static files in express, and you do it like this: 你需要在express中设置静态文件,你这样做:

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 https://expressjs.com/en/starter/static-files.html


Option 2 选项2

Your other option is to send it via sendFile http://expressjs.com/en/api.html#res.sendFile : 您的另一个选择是通过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){})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM