使用JS将JSON文件发送到Express服务器 [英] Sending a JSON file to Express server using JS

查看:194
本文介绍了使用JS将JSON文件发送到Express服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am fairly new to JS and I have a JSON file that I need to send to my server (Express) that I can then parse and use its contents throughout the web app I'm building.

这就是我现在所拥有的:

Here's what I have now:


  • 一个名为data.json的JSON文件

  • 在本地主机上运行的Express服务器设置

  • 一些糟糕的代码:

  • a JSON file named data.json
  • an Express server set up that is running on a localhost
  • some shitty code:

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

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

在上面的代码我只是试图将文件发送到localhost:3000 / search并查看我的JSON文件,但是当我走到那条路径时我收到的是{}。任何人都可以解释一下吗?

In the code above I am just trying to send the file to localhost:3000/search and see my JSON file, but all I receive when I go to that path is { }. Can anyone explain?

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

Any help would be immensely appreciated. Thanks so much in advance.

干杯,
Theo

Cheers, Theo

来自data.json的示例片段:

Example snippet from 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"
}]


推荐答案

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

Just make sure you're requiring the correct file as a variable and then pass that variable into your 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 ,因为它会自动设置标题。

Also, my personal preference is to use res.json as it sets the header automatically.

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

这篇关于使用JS将JSON文件发送到Express服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆