[英]Using Node.js as a simple web server
我想運行一個非常簡單的 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
行。
如何使用一些圖像、CSS 和 JavaScript 為單個 HTML 頁面提供服務?
最簡單的 Node.js 服務器就是:
$ npm install http-server -g
現在您可以通過以下命令運行服務器:
$ cd MyApp
$ http-server
如果您使用的是 NPM 5.2.0 或更新版本,您可以使用http-server
而無需使用npx
安裝它。 不建議在生產中使用它,但它是快速讓服務器在 localhost 上運行的好方法。
$ npx http-server
或者,您可以嘗試此操作,它會打開您的 Web 瀏覽器並啟用 CORS 請求:
$ http-server -o --cors
有關更多選項,請查看GitHub 上的http-server
文檔,或運行:
$ http-server --help
許多其他不錯的功能和對 NodeJit 的簡單部署。
功能叉
當然,您可以使用自己的分叉輕松地充值功能。 您可能會發現它已經在該項目現有的 800 多個分支之一中完成:
Light Server:自動刷新的替代方案
http-server
一個不錯的替代方案是light-server
。 它支持文件監視和自動刷新以及許多其他功能。
$ npm install -g light-server
$ light-server
添加到 Windows 資源管理器中的目錄上下文菜單
reg.exe add HKCR\Directory\shell\LightServer\command /ve /t REG_EXPAND_SZ /f /d "\"C:\nodejs\light-server.cmd\" \"-o\" \"-s\" \"%V\""
簡單的 JSON REST 服務器
如果您需要為原型項目創建一個簡單的 REST 服務器,那么json-server可能就是您要找的。
自動刷新編輯器
大多數網頁編輯器和 IDE 工具現在都包含一個 Web 服務器,該服務器將監視您的源文件並在它們更改時自動刷新您的網頁。
我將Live Server與 Visual Studio Code 一起使用。
開源文本編輯器Brackets還包括一個 NodeJS 靜態 Web 服務器。 只需在 Brackets 中打開任何 HTML 文件,按“實時預覽”,它就會啟動一個靜態服務器並在頁面上打開您的瀏覽器。 每當您編輯和保存 HTML 文件時,瀏覽器都會自動刷新。 這在測試自適應網站時特別有用。 在多個瀏覽器/窗口大小/設備上打開您的 HTML 頁面。 保存您的 HTML 頁面並立即查看您的自適應內容是否正常工作,因為它們都會自動刷新。
Web / SPA / PWA / 移動 / 桌面 / 瀏覽器 Ext Web 開發人員
一些 SPA 框架包含一個內置版本的Webpack DevServer ,可以檢測源文件更改並觸發 SPA 或 PWA Web 應用程序的增量重建和補丁(稱為熱重載)。 這里有一些流行的 SPA 框架可以做到這一點。
VueJS 開發人員
對於 VueJS 開發人員來說,最喜歡的是Quasar Framework ,它包括開箱即用的 Webpack DevServer,帶有支持服務器端渲染 (SSR) 和代理規則的開關,以解決您的 CORS 問題。 它包括大量優化的組件,旨在適應移動和桌面。 這允許你建立適用於所有平台(SPA,SPA + SSR,PWA,PWA + SSR,科爾多瓦和電容移動AppStore的應用程序,電子桌面節點+ VueJS應用程式,甚至瀏覽器擴展)一個應用程序。
另一個流行的是NuxtJS ,它也支持靜態 HTML/CSS 代碼生成以及 SSR 或無 SSR 構建模式,以及其他 UI 組件套件的插件。
反應框架開發人員
Cordova/電容器 + 離子框架開發人員
Iconic 是一個僅限移動設備的混合組件框架,現在支持 VueJS、React 和 Angular 開發。 具有自動刷新功能的本地服務器被烘焙到ionic
工具中。 只需從您的應用程序文件夾運行ionic serve
。 更好的是... ionic serve --lab
可以並排查看iOS和Android的自動刷新視圖。
注意:這個答案是從 2011 年開始的。但是,它仍然有效。
您可以將Connect和ServeStatic與 Node.js 結合使用:
使用 NPM 安裝連接和靜態服務
$ npm install connect serve-static
使用以下內容創建 server.js 文件:
var connect = require('connect'); var serveStatic = require('serve-static'); connect() .use(serveStatic(__dirname)) .listen(8080, () => console.log('Server running on 8080...'));
使用 Node.js 運行
$ node server.js
您現在可以訪問http://localhost:8080/yourfile.html
看看這個要點。 我在這里復制以供參考,但要點已定期更新。
Node.JS 靜態文件 Web 服務器。 將它放在您的路徑中以啟動任何目錄中的服務器,采用可選的端口參數。
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
port = process.argv[2] || 8888;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
更新
要點確實處理 css 和 js 文件。 我自己用過。 在“二進制”模式下使用讀/寫不是問題。 這只是意味着文件不會被文件庫解釋為文本,並且與響應中返回的內容類型無關。
您的代碼的問題是您總是返回“文本/純文本”的內容類型。 上面的代碼不返回任何內容類型,但如果你只是將它用於 HTML、CSS 和 JS,瀏覽器可以很好地推斷出它們。 沒有內容類型比錯誤的內容類型更好。
通常,內容類型是您的 Web 服務器的配置。 因此,如果這不能解決您的問題,我很抱歉,但它作為一個簡單的開發服務器對我有用,並認為它可能會幫助其他一些人。 如果您在響應中確實需要正確的內容類型,您要么需要像 joeytwiddle 那樣明確定義它們,要么使用像 Connect 這樣具有合理默認值的庫。 這樣做的好處是它簡單且自包含(無依賴關系)。
但我確實感覺到你的問題。 所以這是組合解決方案。
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
var contentTypesByExtension = {
'.html': "text/html",
'.css': "text/css",
'.js': "text/javascript"
};
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
var headers = {};
var contentType = contentTypesByExtension[path.extname(filename)];
if (contentType) headers["Content-Type"] = contentType;
response.writeHead(200, headers);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
你不需要快遞。 你不需要連接。 Node.js 原生地執行 http。 您需要做的就是根據請求返回一個文件:
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)
我認為您現在缺少的部分是您正在發送:
Content-Type: text/plain
如果您希望 Web 瀏覽器呈現 HTML,則應將其更改為:
Content-Type: text/html
Step1(在命令提示符內[我希望你 cd 到你的文件夾]): npm install express
第 2 步:創建文件 server.js
var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");
var app = express();
app.use(express.static(__dirname + "/public")); //use static files in ROOT/public folder
app.get("/", function(request, response){ //root dir
response.send("Hello!!");
});
app.listen(port, host);
請注意,您也應該添加 WATCHFILE(或使用 nodemon)。 以上代碼僅適用於簡單的連接服務器。
第 3 nodemon server.js
: node server.js
或nodemon server.js
如果您只想托管簡單的 HTTP 服務器,現在有更簡單的方法。 npm install -g http-server
並打開我們的目錄並輸入http-server
快捷方式:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/../public')); // ← adjust
app.listen(3000, function() { console.log('listening'); });
你的方式:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
console.dir(req.url);
// will get you '/' or 'index.html' or 'css/styles.css' ...
// • you need to isolate extension
// • have a small mimetype lookup array/object
// • only there and then reading the file
// • delivering it after setting the right content type
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('ok');
}).listen(3001);
與其處理 switch 語句,我認為從字典中查找內容類型更簡潔:
var contentTypesByExtension = {
'html': "text/html",
'js': "text/javascript"
};
...
var contentType = contentTypesByExtension[fileExtension] || 'text/plain';
這基本上是已接受的連接版本 3 答案的更新版本:
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic(__dirname, {'index': ['index.html']}));
app.listen(3000);
我還添加了一個默認選項,以便將 index.html 作為默認選項。
你不需要使用任何 NPM 模塊來運行一個簡單的服務器,Node 有一個名為“ NPM Free Server ”的非常小的庫:
50 行代碼,如果您請求文件或文件夾,則輸出,如果工作失敗,則將其顯示為紅色或綠色。 小於 1KB(縮小)。
如果你的 PC 上安裝了 node,你可能有 NPM,如果你不需要 NodeJS 的東西,你可以使用serve包:
1 - 在您的 PC 上安裝軟件包:
npm install -g serve
2 - 為您的靜態文件夾提供服務:
serve <path>
d:> serve d:\StaticSite
它將顯示您的靜態文件夾正在服務哪個端口,只需導航到主機,如:
http://localhost:3000
我在 npm 上發現了一個有趣的庫,可能對你有用。 它被稱為 mime( npm install mime
或https://github.com/broofa/node-mime ),它可以確定文件的 mime 類型。 這是我使用它編寫的網絡服務器示例:
var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path = unescape(__dirname + req.url)
var code = 200
if(fs.existsSync(path)) {
if(fs.lstatSync(path).isDirectory()) {
if(fs.existsSync(path+"index.html")) {
path += "index.html"
} else {
code = 403
resp.writeHead(code, {"Content-Type": "text/plain"});
resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
}
resp.writeHead(code, {"Content-Type": mime.lookup(path)})
fs.readFile(path, function (e, r) {
resp.end(r);
})
} else {
code = 404
resp.writeHead(code, {"Content-Type":"text/plain"});
resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(9000,"localhost");
console.log("Listening at http://localhost:9000")
這將提供任何常規文本或圖像文件(.html、.css、.js、.pdf、.jpg、.png、.m4a 和 .mp3 是我測試過的擴展名,但理論上它應該適用於所有內容)
這是我用它得到的輸出示例:
Listening at http://localhost:9000
GET 200 OK /cloud
GET 404 Not Found /cloud/favicon.ico
GET 200 OK /cloud/icon.png
GET 200 OK /
GET 200 OK /501.png
GET 200 OK /cloud/manifest.json
GET 200 OK /config.log
GET 200 OK /export1.png
GET 200 OK /Chrome3DGlasses.pdf
GET 200 OK /cloud
GET 200 OK /-1
GET 200 OK /Delta-Vs_for_inner_Solar_System.svg
注意路徑構造中的unescape
函數。 這是為了允許帶有空格和編碼字符的文件名。
Node.js 示例應用程序節點聊天具有您想要的功能。
在它的README.textfile
3. Step 是你要找的。
第1步
- 創建一個在端口 8002 上響應 hello world 的服務器
第2步
- 創建一個 index.html 並提供它
第三步
- 介紹 util.js
- 更改邏輯以便提供任何靜態文件
- 如果找不到文件,則顯示 404
第四步
- 添加 jquery-1.4.2.js
- 添加客戶端.js
- 更改 index.html 以提示用戶輸入昵稱
這是util.js
我這樣做的方法是首先通過全局安裝節點靜態服務器
npm install node-static -g
然后導航到包含您的 html 文件的目錄並使用static
啟動靜態服務器。
轉到瀏覽器並輸入localhost:8080/"yourHtmlFile"
。
基本上是復制接受的答案,但避免創建 js 文件。
$ node
> var connect = require('connect'); connect().use(static('.')).listen(8000);
發現它非常方便。
在最新版本的 Express 中,serve-static 已經成為一個獨立的中間件。 使用它來服務:
require('http').createServer(require('serve-static')('.')).listen(3000)
首先安裝serve-static
。
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/html'});
// change the to 'text/plain' to 'text/html' it will work as your index page
res.end(index);
}).listen(9615);
我想你在哪里尋找這個。 在你的 index.html 中,簡單地用普通的 html 代碼填充它 - 無論你想在它上面呈現什么,比如:
<html>
<h1>Hello world</h1>
</html>
我使用下面的代碼來啟動一個簡單的 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 內容。
同意聲明“沒有內容類型總比錯誤的好”
來自 w3schools
創建一個節點服務器來為請求的任何文件提供服務非常容易,並且您不需要為其安裝任何軟件包
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
http://localhost:8080/file.html
將從磁盤提供 file.html
我不確定這是否正是您想要的,但是,您可以嘗試更改:
{'Content-Type': 'text/plain'}
對此:
{'Content-Type': 'text/html'}
這將使瀏覽器客戶端將文件顯示為 html 而不是純文本。
Express 函數 sendFile 正是您所需要的,並且由於您希望從節點獲得 Web 服務器功能,因此 Express 成為自然選擇,然后提供靜態文件變得如此簡單:
res.sendFile('/path_to_your/index.html')
在這里閱讀更多: https : //expressjs.com/en/api.html#res.sendFile
一個帶有用於節點的快速 Web 服務器的小示例:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
運行它,並導航到http://localhost:8080
為了擴展這一點以允許您提供諸如 css 和圖像之類的靜態文件,這是另一個示例:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/css'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
因此,創建一個名為 css 的子文件夾,將您的靜態內容放入其中,它將可用於您的 index.html 以便於參考,例如:
<link type="text/css" rel="stylesheet" href="/css/style.css" />
注意 href 中的相對路徑!
瞧!
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(9615);
//Just Change The CONTENT TYPE to 'html'
一個稍微詳細一點的 express 4.x 版本,但它提供目錄列表、壓縮、緩存和請求以最少的行數記錄
var express = require('express');
var compress = require('compression');
var directory = require('serve-index');
var morgan = require('morgan'); //logging for express
var app = express();
var oneDay = 86400000;
app.use(compress());
app.use(morgan());
app.use(express.static('filesdir', { maxAge: oneDay }));
app.use(directory('filesdir', {'icons': true}))
app.listen(process.env.PORT || 8000);
console.log("Ready To serve files !")
這里有大量復雜的答案。 如果您不打算處理 nodeJS 文件/數據庫,而只想按照您的問題建議提供靜態 html/css/js/images,那么只需安裝pushstate-server模塊或類似模塊;
這是一個“one liner”,它將創建和啟動一個迷你站點。 只需將整個塊粘貼到終端中的相應目錄中即可。
mkdir mysite; \
cd mysite; \
npm install pushstate-server --save; \
mkdir app; \
touch app/index.html; \
echo '<h1>Hello World</h1>' > app/index.html; \
touch server.js; \
echo "var server = require('pushstate-server');server.start({ port: 3000, directory: './app' });" > server.js; \
node server.js
打開瀏覽器並轉到http://localhost:3000 。 完畢。
服務器將使用app
目錄作為根來提供文件。 要添加其他資產,只需將它們放在該目錄中。
對於簡單的nodejs server
已經有一些很好的解決方案。 如果您在更改文件時需要live-reloading
,還有一個解決方案。
npm install lite-server -g
導航您的目錄並執行
lite-server
它將通過實時重新加載為您打開瀏覽器。
上面的大多數答案都很好地描述了如何提供內容。 我正在尋找的附加內容是目錄列表,以便可以瀏覽目錄的其他內容。 這是我為更多讀者提供的解決方案:
'use strict';
var finalhandler = require('finalhandler');
var http = require('http');
var serveIndex = require('serve-index');
var serveStatic = require('serve-static');
var appRootDir = require('app-root-dir').get();
var log = require(appRootDir + '/log/bunyan.js');
var PORT = process.env.port || 8097;
// Serve directory indexes for reports folder (with icons)
var index = serveIndex('reports/', {'icons': true});
// Serve up files under the folder
var serve = serveStatic('reports/');
// Create server
var server = http.createServer(function onRequest(req, res){
var done = finalhandler(req, res);
serve(req, res, function onNext(err) {
if (err)
return done(err);
index(req, res, done);
})
});
server.listen(PORT, log.info('Server listening on: ', 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
應該和這個文件在同一個目錄下。 希望這對某人有所幫助:)
本地網絡服務器絕對值得一看! 這是自述文件的摘錄:
用於快速全棧開發的精益模塊化 Web 服務器。
使用此工具:
Local-web-server 是一個lws的發行版,捆綁了一個有用的中間件的“入門包”。
這個包安裝了ws
命令行工具(查看使用指南)。
不帶任何參數運行ws
會將當前目錄作為靜態網站托管。 如果該文件存在,導航到服務器將呈現目錄列表或您的index.html
。
$ ws
Listening on http://mbp.local:8000, http://127.0.0.1:8000, http://192.168.0.100:8000
此剪輯演示了靜態托管以及幾種日志輸出格式 - dev
和stats
。
為單頁應用程序(具有客戶端路由的應用程序,例如 React 或 Angular 應用程序)提供服務就像指定單頁的名稱一樣簡單:
$ ws --spa index.html
對於靜態站點,對典型 SPA 路徑(例如/user/1
、 /login
)的請求將返回404 Not Found
因為該位置的文件不存在。 但是,通過將index.html
標記為 SPA,您可以創建此規則:
如果請求靜態文件(例如/css/style.css
),則提供它,如果沒有(例如/login
),則提供指定的 SPA 並處理客戶端的路由。
另一個常見用例是將某些請求轉發到遠程服務器。
以下命令將博客帖子請求從以/posts/
開頭的任何路徑代理到https://jsonplaceholder.typicode.com/posts/
。 例如,對/posts/1
的請求將被代理到https://jsonplaceholder.typicode.com/posts/1
。
$ ws --rewrite '/posts/(.*) -> https://jsonplaceholder.typicode.com/posts/$1'
重寫教程。
此剪輯演示了上述加上使用--static.extensions
指定默認文件擴展名和--verbose
來監視活動。
對於 HTTPS 或--http2
分別傳遞--https
或--http2
標志。 有關更多配置選項和有關如何在瀏覽器中獲取“綠色掛鎖”的指南,請參閱 wiki 。
$ lws --http2
Listening at https://mba4.local:8000, https://127.0.0.1:8000, https://192.168.0.200:8000
沒有第三方框架; 允許查詢字符串; 添加尾部斜線; 把手 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...')});
這是我用來快速查看網頁的最快解決方案之一
sudo npm install ripple-emulator -g
從那時起,只需輸入 html 文件的目錄並運行
ripple emulate
然后將設備更改為 Nexus 7 橫向。
我也可以推薦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")
}
}
}
今天有大量的圖書館,很容易。 這里的答案是功能性的。 如果您想要更快更簡單的另一個版本
當然先安裝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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.