Javascript NodeJS Express-返回它触发的URL路径的JSON文件
我试图编写一个NodeJS项目,从项目目录中读取JSON文件,并在用户触发特定URL时响应JSON文件数据 对于下面的项目,当我触发Javascript NodeJS Express-返回它触发的URL路径的JSON文件,javascript,json,node.js,api,express,Javascript,Json,Node.js,Api,Express,我试图编写一个NodeJS项目,从项目目录中读取JSON文件,并在用户触发特定URL时响应JSON文件数据 对于下面的项目,当我触发http://localhost:8081/api/user在web浏览器中 为了实现这一点,我必须显式地硬编码一个响应特定URL的函数。例如,如果我想在api文件夹中再添加1个JSON文件并允许用户访问它,我必须显式地硬编码另一个函数来响应不同的请求 app.get('/api/newJSONFile', (req, res) => { fs
http://localhost:8081/api/user
在web浏览器中
为了实现这一点,我必须显式地硬编码一个响应特定URL的函数。例如,如果我想在api文件夹
中再添加1个JSON文件并允许用户访问它,我必须显式地硬编码另一个函数来响应不同的请求
app.get('/api/newJSONFile', (req, res) => {
fs.readFile( __dirname +'/api/newJSONFile' +".json", 'utf8', function (err, data) {
res.send(data);
res.end( data );
});
});
因此,在添加代码之后,用户将能够通过http://localhost:8081/api/newJsonFile
。没有显式硬代码
当启动http://localhost:8081/api/newJsonFile
我的问题:
const express = require('express');
const app = express();
const fs = require("fs");
app.get('/api/user', (req, res) => {
fs.readFile( __dirname +'/api/user' +".json", 'utf8', function (err, data) {
res.send(data);
res.end( data );
});
});
var server = app.listen(8081, () => {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
表示支持
因此,从url中获取任意字符串就像修改路由到:
app.get('/api/:file', (req, res) => {
fs.readFile( __dirname +'/api/' + req.params.file + ".json", 'utf8', function (err, data) {
res.send(data);
res.end( data );
});
});
您可以在url中使用文件名,然后只使用一个路由处理程序来传递JSON文件
app.get('/api/:jsonFile', (req, res) => {
fs.readFile( __dirname +'/api/' + req.params.jsonFile +".json", 'utf8', function (err, data) {
res.send(data);
res.end( data );
});
});
添加适当的错误处理,如文件不存在,然后使用如下方式发回404
:
if (!fs.existsSync(path)) {
res.status(404).send("");
}
编辑:
要返回漂亮的JSON对象,请尝试使用以下命令:
res.header("Content-Type",'application/json');
res.send(JSON.stringify(YOUR_JSON_OBJECT, null, 4));
您可以使用提供指定文件夹中的静态json文件
const express = require('express');
const app = express();
// Setup express static middleware to look for files in the api directory for all requests starting with /api
app.use('/api', express.static('api') , function(req, res){
// Optional 404 handler
res.status(404);
res.json({error:{code:404}})
});
var server = app.listen(8081, () => {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
然后,您可以访问localhost:8081/api/user.json
文件夹中的user.json
编辑:
如果你想添加多个文件夹,你可以创建一个指定的公共
(实际上你可以称之为任何东西)目录,并将所有顶级文件夹放在那里
考虑以下以嵌套方式存储的JSON文件:
/public/api/user.json
[api文件夹中的一级嵌套]
/public/data/config.json
[数据文件夹中的一级嵌套]
/public/data/server/config.json
[数据->服务器文件夹中的两级嵌套]
然后你就可以做了
const express = require('express');
const app = express();
// EDIT: added options to ensure json can be accessed without extension
app.use(express.static('public',{index:false, extensions:['json']}));
app.use(function (req, res) {
// Optional 404 handler
res.status(404);
res.json({
error: {
code: 404
}
});
})
var server = app.listen(8081, () => {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
然后通过以下方式访问您的文件:
localhost:8081/api/user.json
或localhost:8081/api/user
localhost:8081/data/config.json
或localhost:8081/data/config
localhost:8081/data/server/config.json
或localhost:8081/data/server/config
额外改进 注意:此方法可能会意外地公开敏感的服务器端配置文件[如
package.json
]以及整个代码库。请小心使用此方法,并且只有在您知道自己在做什么的情况下
如果您不想创建指定目录(在本例中为“公用”文件夹)并将所有顶级文件夹放在其中以访问它,则可以使用下面的代码动态地为您的文件提供服务:
const express = require('express');
const app = express();
var publicdir = __dirname + '/';
app.use(express.static(publicdir,{extensions:['json']})); //or ,{index:false, extensions:['json']}
app.use(function (req, res) {
res.status(404);
res.json({
error: {
code: 404
}
});
})
var server = app.listen(8081, () => {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
对于“/api”,文件夹似乎也需要硬编码。是否可以使其自动检测文件夹URL?例如,我添加了一个包含其他json文件的新文件夹,我不需要声明另一个use()函数。@EricWong Yup,您可以这样做,但您可能需要稍微重新组织一下文件夹结构。请参阅我编辑的答案BTW,是否可以使URL不需要放置文件扩展名“.json”来加载文件?例如,localhost:8081/api/user而不是localhost:8081/api/user.jsi我想我找到了解决方案,使用感谢,接受了您对语法和附加方法的编辑。您添加的附加方法非常危险。使用静态中间件公开服务器根从来都不是一个好主意[通过静态文件服务可以访问整个代码库]。但是,我保留了编辑,因为它符合您提出的问题。这实际上也很有效,是否有任何方法可以输出格式良好的JSON数据?我尝试了这个>obj=JSON.parse(数据);res.send(obj);<但是JSON数据似乎没有格式化。@EricWong我修改了我的答案以发回漂亮的JSON。看看这是否适用于您。在我的例子中,它写道,res.send(JSON.stringify(data,null,4));你是否也添加了
res.header
?然后你可以使用nodejsreaddirsync
读取和处理目录以查找json文件。看看