All*_*lan 5 json node.js express
我想用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));
});
Run Code Online (Sandbox Code Playgroud)
data.json看起来像这样
[{
"param": "one",
"param": "two",
"param": "three"
}]
Run Code Online (Sandbox Code Playgroud)
我还为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();
}
Run Code Online (Sandbox Code Playgroud)
我收到了回复,但它是一个空的对象.我猜这是因为我的服务器文件var data = {};是空的但我不知道该怎么办呢?
Vip*_*pin 12
你为什么不直接发送你要求的文件
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'));
});
Run Code Online (Sandbox Code Playgroud)
但是,如果您只想做代码,那么您需要在代码中包含的内容就是
data.json文件.data变量中.要读取该文件,您需要包含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 */
Run Code Online (Sandbox Code Playgroud)
异步:
var fs = require('fs');
var data;
fs.readFile('/src/assets/data.json', 'utf8', function (err, data) {
if (err) throw err;
data = JSON.parse(data);
});
Run Code Online (Sandbox Code Playgroud)
请在应用代码之前阅读官方文档,并随时查看节点文件系统上的其他示例.
来源:这里
| 归档时间: |
|
| 查看次数: |
4547 次 |
| 最近记录: |