2017-11-11 82 views
0

我想使用express對本地JSON文件進行GET請求。如何使用express.js將GET請求發送到本地json文件?

在我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 = {};是空的,但我不知道該怎麼辦?

回答

4

你爲什麼不只是簡單地發送給您請求

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變量。

讀取該文件,則需要包括File System模塊的Node.js的

同步:

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); 
}); 

請仔細閱讀申請前的官方文檔代碼,也可以隨時查看節點文件系統上的其他示例。

來源:Here

+0

非常感謝。 – Allan

+0

請考慮upvoting答案。 @allan – imvpn22