【问题标题】:How to make GET request with express.js to a local json file?如何使用 express.js 向本地 json 文件发出 GET 请求?
【发布时间】:2018-04-24 12:25:36
【问题描述】:

我想使用 express 向本地 JSON 文件发出 GET 请求。

在我的 server.js 中有这个

var data = {};
app.get('/src/assets/data.json', (req, res) => {
  console.log(res)
  res.writeHead(200, {
    'Content-type': 'application/json'
  });

  res.end(JSON.stringify(data));
});

data.json 看起来像这样

[{
    "param": "one",
    "param": "two",
    "param": "three"
  }]

我还为 GET 请求创建了一个函数,该函数在 DOM 加载后立即调用

getData() {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', '/src/assets/data.json', true);
    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        console.log(xhr)
      }
    };
    xhr.send();
  }

我收到了回复,但它是一个空对象。我猜这是因为在我的服务器文件中var data = {}; 是空的,但我不确定如何处理它?

【问题讨论】:

    标签: json node.js express


    【解决方案1】:

    你为什么不直接发送你要求的文件

    var data = {};
    app.get('/src/assets/data.json', (req, res) => {
      console.log(res)
    
      /* Insted of doing all this */
      // res.writeHead(200, {
      //    'Content-type': 'application/json'
      // });
      // res.end(JSON.stringify(data));
    
      /* Just send the file */
      res.sendFile(path.join(__dirname, '/src/assets', 'data.json'));
    });
    

    但如果你只想做你的代码,你需要包含在你的代码中的是

    1. 读取data.json 文件。
    2. 将文件中的所有数据放入对象中,即data变量。

    要读取文件,你需要包含 Node.js 的 File System 模块

    同步:

    var fs = require('fs'); /* Put it where other modules included */
    var data = JSON.parse(fs.readFileSync('/src/assets/data.json', 'utf8')); /* Inside the get function */
    

    异步:

    var fs = require('fs');
    var data;
    fs.readFile('/src/assets/data.json', 'utf8', function (err, data) {
      if (err) throw err;
      data = JSON.parse(data);
    });
    

    在应用代码之前请阅读官方文档,也可以随意查看 Node File System 上的其他示例。

    来源:Here

    【讨论】:

      【解决方案2】:

      您可以创建一个本地的rest服务器并返回json格式保存在一个文件中:

      文件 app.js

      'use strict'
      
      var http = require('http');
      var url = require('url');
      var fs = require('fs');
      var path = require('path');
      
      http.createServer((request, response) => {
        let urlInfo = url.parse(request.url, true); // host, pathname, search
        let method = request.method;
      
        if (method == 'GET') {
      	  console.log(urlInfo.pathname);
      	 if (urlInfo.pathname.includes('request1') ) {
      		sendResponse('./request1.txt',response)
      
          } 
        } else {
          sendResponse("", "")
        }
      }).listen(3000,"192.168.0.1");       // change your local host here
      console.log("Start server at port 3000");
      
      function sendResponse(filename,response) {
      	var sampleTxt = path.join(__dirname, filename);
      	console.log(filename);
      	fs.readFile(sampleTxt, function(error, data) {
      	  if (error) return console.error(error);
      		response.writeHead(200, {'Content-Type': 'application/json;charset=UTF-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS', "Access-Control-Allow-Headers": "If-Modified-Since"});
      	    response.write(data);
      		response.end();
      	  
      	});
      }

      在文件 request1.txt => 保存你想要的响应格式

      [
        {
          "uuid": "id1",
          "userId": 80778,
          "mac": "mac1",
          "name": "Living & Dining Room"
        },
        {
          "uuid": "id2",
          "userId": 80778,
          "mac": "mac2",
          "name": "Bed Room"
        },
        {
          "uuid": "id3",
          "userId": 80778,
          "mac": "mac3",
          "name": "Kitchen"
        }
      ]

      运行 app.js

      【讨论】:

        猜你喜欢
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 2019-07-19
        • 2020-05-07
        • 2013-05-28
        • 2016-05-22
        • 1970-01-01
        • 2019-03-10
        相关资源
        最近更新 更多