[英]How to create a file from an http get response using Node + Express without setting the response type
[英]How to require a JSON file with a node HTTP server response (without express)
我刚刚设置了我的第一个节点 HTTP 服务器,我试图从我的应用程序中的 JSON 文件中获取响应数据。 当我在 server.js 文件中声明 JSON object 时,一切正常。
data = "{"sample json" : "this is a test"}";
但我想用 static JSON 文件替换data
data/sample.json
这是我的server.js
文件中的示例
const http = require("http");
const hostname = "localhost";
const port = 3000;
const server = http.createServer(function(req, res) {
data = // this is where I want to get the JSON data from data/sample.json
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(data);
res.end();
});
用 fs.readFile() 解决
const http = require("http");
const hostname = "localhost";
const port = 3000;
const fs = require('fs');
const server = http.createServer(function(req, res) {
filePath = './data/sample.json';
fs.readFile(filePath, function(error, content) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(content);
});
});
以防其他人遇到这个问题。 上面的答案有很多错别字和错误,而且不完整。 这是一个可行的解决方案。
const http = require("http");
const hostname = "localhost";
const fs = require('fs');
const port = 8080;
const server = http.createServer(function(req, res) {
filePath = './data/sample.json';
if (req.url == '/api/data') {
fs.readFile(filePath, function(error, content) {
if (error) {
if (error.code == 'ENOENT') {
res.writeHead(404);
res.end(error.code);
}
else {
res.writeHead(500);
res.end(error.code);
}
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(content);
}
});
}
else {
res.writeHead(404);
res.end('404 NOT FOUND');
}
});
server.listen(port, hostname, () => {
console.log('Server started on port ', port);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.