我想运行一个非常简单的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。后:
> # module with zero dependencies
> npm install -g @kawix/core@latest
> # change /path/to/static with your folder or empty for current
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" /path/to/static
这里是“https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js”的内容(你不需要下载,我贴出来是为了了解后面的工作原理)
// you can use like this:
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" /path/to/static
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js"
// this will download the npm module and make a local cache
import express from 'npm://express@^4.16.4'
import Path from 'path'
var folder= process.argv[2] || "."
folder= Path.resolve(process.cwd(), folder)
console.log("Using folder as public: " + folder)
var app = express()
app.use(express.static(folder))
app.listen(8181)
console.log("Listening on 8181")
这很容易,因为今天有大量的图书馆。这里的答案是功能性的。如果你想要另一个版本开始更快和简单
当然,首先要安装node.js。后:
> # module with zero dependencies
> npm install -g @kawix/core@latest
> # change /path/to/static with your folder or empty for current
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" /path/to/static
这里是“https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js”的内容(你不需要下载,我贴出来是为了了解后面的工作原理)
// you can use like this:
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" /path/to/static
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js"
// this will download the npm module and make a local cache
import express from 'npm://express@^4.16.4'
import Path from 'path'
var folder= process.argv[2] || "."
folder= Path.resolve(process.cwd(), folder)
console.log("Using folder as public: " + folder)
var app = express()
app.use(express.static(folder))
app.listen(8181)
console.log("Listening on 8181")
我也可以推荐SugoiJS,它很容易设置,并提供了一个快速开始编写的选项,有很好的功能。
看看这里:http://demo.sugoijs.com/
,文档:https://wiki.sugoijs.com/
它具有请求处理装饰器、请求策略和授权策略装饰器。
例如:
import {Controller,Response,HttpGet,RequestParam} from "@sugoi/server";
@Controller('/dashboard')
export class CoreController{
constructor(){}
@HttpGet("/:role")
test(@RequestParam('role') role:string,
@RequestHeader("role") headerRole:string){
if(role === headerRole )
return "authorized";
else{
throw new Error("unauthorized")
}
}
}
我遇到的更简单的版本如下。出于教育目的,它是最好的,因为它不使用任何抽象库。
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"mp3":"audio/mpeg",
"mp4":"video/mp4",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"};
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
console.log("not exists: " + filename);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
res.writeHead(200, {'Content-Type':mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}); //end path.exists
}).listen(1337);
现在进入浏览器,打开以下内容:
http://127.0.0.1/image.jpg
这里image.jpg应该和这个文件在同一个目录下。
希望这能帮助到一些人:)
创建一个简单的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