我想使用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 = {};
是空的,但我不知道该如何处理它?</ p>
答案 0 :(得分:11)
为什么不简单地发送您要求的文件
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'));
});
但是,如果您只想做代码,那么您需要在代码中包含的内容是
data.json
文件。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);
});
在应用代码之前,请阅读官方文档,并随时查看节点文件系统上的其他示例。
来源:Here
答案 1 :(得分:1)
您可以创建本地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