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

The*_*uss 9 javascript json node.js express

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

这就是我现在拥有的:

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

    app.get('/ search',function(req,res){res.header("Content-Type",'application/json'); 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"
}]
Run Code Online (Sandbox Code Playgroud)

Kha*_*uri 12

只需确保您需要将正确的文件作为变量,然后将该变量传递给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));
})
Run Code Online (Sandbox Code Playgroud)

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

app.get('/search', function (req, res) {
  res.json(data);
})
Run Code Online (Sandbox Code Playgroud)


Ian*_*Ian 8

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

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

该代码假定该文件与 JS 代码位于同一目录中。这个答案解释了这是如何工作的。