javascript - express.js 在终端中获取 json 文件

标签 javascript json node.js rest express

如何使用 express.js 获取 JSON 文件?我希望能够在我的 Mac 终端中访问它。我正在做一项大学作业,要求我编写一个 HTTP 服务器来充当简单的数据存储。它必须响应 GET、PUT、POST 和 DELETE 请求。我必须为此应用程序使用 express.js 而不是 fs。

到目前为止,在我的根目录中有一个 server.js 文件和一个名为 lib 的子目录,其中包含另一个名为 notes 的子目录。 Notes 是 JSON 文件所在的位置。

在我的根目录中,我有一个 server.js 文件。这是我到目前为止的全部内容:

'use strict'
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var notes = './lib/notes';

app.use(bodyParser.json());

app.get('/', function(req, res) {
  //
  //this is the part I need help with
  //
}

var port = process.env.PORT || 3000;
app.listen(port, function() {
  console.log('Server started on port ' + port;
});

一旦我的 GET 请求生效,我应该能够从我的 Mac 终端发送 GET 请求并接收 notes 目录中的所有 JSON 文件。

最佳答案

...from my Mac terminal I should be able to send a GET request and receive all JSON files inside the notes directory.

如果你不想使用 fs 模块(当然你也不需要),

您可以简单地为 GET 请求设置一个路由,并使用 app.sendFile() 发送 json 文件作为响应

app.get('/',function(req,res){
    res.sendFile(path.normalize(__dirname + '/foo.json'))  
   //assuming your app.js and json file are at same level. 
   //You may change this to 'lib/notes/foo.json' to fit you case
})

path 是您需要 require() 的模块。

__dirname 是当前执行脚本所在的目录。

最后 foo.json 是包含你的 json 的文件

{
    "name":"nalin",
    "origin":"stackoverflow"
}

这是app.js的完整代码

var express = require('express');
var path = require('path');
var app  = express();


app.get('/',function(req,res){
    res.sendFile(path.normalize(__dirname + '/foo.json'))
})

app.listen(3000);

这将帮助您使用 node app.js 运行 Node 服务器。

最后你可以通过by访问json了

  • 在浏览器上访问 http://localhost:3000/
  • 在你的 mac 终端上运行 curl 命令 curl localhost:3000

希望这对您有所帮助。

关于javascript - express.js 在终端中获取 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468409/

相关文章:

javascript - Facebook Messenger 机器人 : Understanding Export Arguments

java - 如何使用Apache Avro序列化JSON文档,然后写入Cassandra?

c# - 当使用 JSON 中的重复键反序列化字典时,如何强制抛出异常?

html - 我如何将值从 Angular 形式转移到服务器nodejs

python - 如何在本地测试 aws lambda 函数

javascript - Node JS Chat - 判断是否导航到页面或关闭窗口

javascript - 我可以禁用 IE10 历史滑动手势吗?

javascript - 如何从 findOne() Mongoose 返回结果

javascript - jQuery 单击表格行切换部分

json - 通过 AJAX Post 使用 JSON 将数据传递到 CFC 函数