我想运行一个非常简单的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执行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)
我遇到的更简单的版本如下。出于教育目的,它是最好的,因为它不使用任何抽象库。
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应该和这个文件在同一个目录下。
希望这能帮助到一些人:)
我也可以推荐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")
}
}
}