使用JS将JSON文件发送到Express服务器

时间:2017-06-30 14:41:33

标签: javascript json node.js express

我是JS的新手,我有一个JSON文件,我需要发送到我的服务器(Express),然后我可以解析并在我构建的网络应用程序中使用它的内容。

这就是我现在所拥有的:

  • 名为data.json的JSON文件
  • 在localhost上运行的Express服务器设置
  • 一些糟糕的代码:

    app.get(' / search',function(req,res){  res.header("内容类型"'应用/ JSON&#39);  res.send(JSON.stringify({/ data.json /})); });

在上面的代码中,我只是尝试将文件发送到localhost:3000 / search并查看我的JSON文件,但是当我走到那条路径时我收到的是{}。谁能解释一下?

任何帮助都会非常感激。非常感谢提前。

干杯, 西奥

data.json中的示例代码段:

[{
    "name": "Il Brigante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-0.png"
}, {
    "name": "Giardino Doro Ristorante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-1.png"
}]

5 个答案:

答案 0 :(得分:9)

请确保您需要将正确的文件作为变量,然后将该变量传递到res.send!

const data = require('/path/to/data.json')

app.get('/search', function (req, res) {
  res.header("Content-Type",'application/json');
  res.send(JSON.stringify(data));
})

此外,我个人的偏好是使用res.json,因为它会自动设置标题。

app.get('/search', function (req, res) {
  res.json(data);
})

答案 1 :(得分:2)

尝试res.json(data.json)而不是res.send(...

答案 2 :(得分:2)

另一种选择是使用sendFile并设置内容类型标题。

app.get('/search', (req, res) => {
    res.header("Content-Type",'application/json');
    res.sendFile(path.join(__dirname, 'file_name.json'));
})

代码假定文件与JS代码位于同一目录中。 answer对此进行了解释。

答案 3 :(得分:0)

首先读取文件,然后将json发送给客户端。

fs.readFile('file_name.json', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
  res.send(JSON.stringify(obj));
});

答案 4 :(得分:0)

因为 __dirname 解析为运行脚本的位置,所以我更喜欢使用 path.resolve()

var path = require('path');

app.get('/search', (req, res) => {
    res.header("Content-Type",'application/json');
    res.sendFile(path.resolve('search/data.json'));
})