我想运行一个非常简单的HTTP服务器。对example.com的每个GET请求都应该得到index.html,但作为一个常规的HTML页面(即,与阅读普通网页时的体验相同)。
使用下面的代码,我可以读取index.html的内容。我如何服务index.html作为一个普通的网页?
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(index);
}).listen(9615);
下面的一个建议很复杂,需要我为我想使用的每个资源(CSS、JavaScript、图像)文件写一个get行。
我如何能提供一个单一的HTML页面与一些图像,CSS和JavaScript?
创建一个简单的Node.js Web服务器,并从一个文件异步服务一个HTML页面
创建我的第一个node.js服务器时,我找到了一个简单而有效的方法来做到这一点。
我们可以在开始时加载一次HTML,而不是为每个请求加载HTML。然后返回我们在启动时加载的数据。
const host = "localhost";
const port = 5000;
const http = require("HTTP");
const fs = require("fs").promises;
let htmlFile;
const reqListenerFunc = function (req, resp) {
resp.setHeader("Content-Type", "text/html");
resp.writeHead(200);
resp.end(htmlFile);
};
const simpleServer = http.createServer(reqListenerFunc);
// // Using Arrow function directly
// const simpleServer = http.createServer( (req, resp) => {
// resp.setHeader("Content-Type", "text/html");
// resp.writeHead(200);
// resp.end(htmlFile);
// });
fs.readFile(__dirname + "/index.html")
.then(content => {
htmlFile = content;
simpleServer.listen(port, host, () => {
console.log(`Node.js web server is running on http://${host}:${port}`);
});
})
.catch(err => {
console.error(`Cannot read index.html file. <br> Error: ${err}`);
process.exit(1);
});
阅读更多信息:https://www.digitalocean.com/community/tutorials/how-to-create-a-web-server-in-node-js-with-the-http-module
Node.js webserver
没有第三方框架;允许查询字符串;添加尾随斜杠;处理404
创建一个public_html子文件夹,并将所有内容放在其中。
要点:https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3
var fs = require('fs');
require('http').createServer(function(request, response) {
var path = 'public_html'+ request.url.slice(0,
(request.url.indexOf('?')+1 || request.url.length+1) - 1);
fs.stat(path, function(bad_path, path_stat) {
if (bad_path) respond(404);
else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
response.setHeader('Location', path.slice(11)+'/');
respond(301);
} else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
function(bad_file, file_content) {
if (bad_file) respond(404);
else respond(200, file_content);
});
});
function respond(status, content) {
response.statusCode = status;
response.end(content);
}
}).listen(80, function(){console.log('Server running on port 80...')});
你不需要快递。你不需要联系。Node.js执行http native。你所需要做的就是根据请求返回一个文件:
var http = require('http')
var url = require('url')
var fs = require('fs')
http.createServer(function (request, response) {
var requestUrl = url.parse(request.url)
response.writeHead(200)
fs.createReadStream(requestUrl.pathname).pipe(response) // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync)
}).listen(9615)
一个更完整的例子,确保请求不能访问基目录下的文件,并进行适当的错误处理:
var http = require('http')
var url = require('url')
var fs = require('fs')
var path = require('path')
var baseDirectory = __dirname // or whatever base directory you want
var port = 9615
http.createServer(function (request, response) {
try {
var requestUrl = url.parse(request.url)
// need to use path.normalize so people can't access directories underneath baseDirectory
var fsPath = baseDirectory+path.normalize(requestUrl.pathname)
var fileStream = fs.createReadStream(fsPath)
fileStream.pipe(response)
fileStream.on('open', function() {
response.writeHead(200)
})
fileStream.on('error',function(e) {
response.writeHead(404) // assume the file doesn't exist
response.end()
})
} catch(e) {
response.writeHead(500)
response.end() // end the response so browsers don't hang
console.log(e.stack)
}
}).listen(port)
console.log("listening on port "+port)
我使用下面的代码来启动一个简单的web服务器,如果Url中没有提到文件,它会渲染默认的html文件。
var http = require('http'),
fs = require('fs'),
url = require('url'),
rootFolder = '/views/',
defaultFileName = '/views/5 Tips on improving Programming Logic Geek Files.htm';
http.createServer(function(req, res){
var fileName = url.parse(req.url).pathname;
// If no file name in Url, use default file name
fileName = (fileName == "/") ? defaultFileName : rootFolder + fileName;
fs.readFile(__dirname + decodeURIComponent(fileName), 'binary',function(err, content){
if (content != null && content != '' ){
res.writeHead(200,{'Content-Length':content.length});
res.write(content);
}
res.end();
});
}).listen(8800);
它将呈现所有的js, css和图像文件,以及所有的html内容。
同意“没有内容类型比错误的内容类型更好”的说法