http-server 是一個簡單的零配置命令行HTTP服務器, 基于 nodeJs.
參考鏈接 https://www.npmjs.com/package/http-server
-p 端口號 (默認 8080)
-a IP 地址 (默認 0.0.0.0)
-d 顯示目錄列表 (默認 'True')
-i 顯示 autoIndex (默認 'True')
-e or --ext 如果沒有提供默認的文件擴展名(默認 'html')
-s or --silent 禁止日志信息輸出
--cors 啟用 CORS via the Access-Control-Allow-Origin header
-o 在開始服務后打開瀏覽器
-c 為 cache-control max-age header 設置Cache time(秒) , e.g. -c10 for 10 seconds (defaults to '3600'). 禁用 caching, 則使用 -c-1.
-U 或 --utc 使用UTC time 格式化log消息
-P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com
-S or --ssl 啟用 https
-C or --cert ssl cert 文件路徑 (default: cert.pem)
-K or --key Path to ssl key file (default: key.pem)
-r or --robots Provide a /robots.txt (whose content defaults to 'User-agent: *\nDisallow: /')
-h or --help 打印以上列表并退出
命令行
安裝 npm install http-server -g
啟動http-server命令就是在cmd下直接輸入http-server
狈蚤,之后就可以瀏覽器訪問http://localhost:8080.
默認web目錄是當前目錄恬试,想改變web目錄的話轿腺,在命令后面加上本地路徑http-server <path_of_project>
JS文件
通過node xxx.js
運行
let http = require('http');
let url = require('url');
let fs = require('fs');
let server = http.createServer((req,res)=>{
var pathname = url.parse(req.url).pathname; //獲取url的pathname (/index.html)
fs.readFile(pathname.substring(1), function (err,data) { //fs模塊加載文件
if(err){
res.writeHead(404,{
'Content-Type':'text/html'
});
}else{
res.writeHead(200,{
'Content-Type':'text/html'
});
res.write(data.toString());
}
res.end();
});
});
server.listen(3000,'127.0.0.1', ()=>{
console.log("服務器已經(jīng)運行遭铺,請打開瀏覽,輸入:http://127.0.0.1:3000/ 來進行訪問.")
});
也可以簡單地構(gòu)造一個新的url蛮穿,返回一個json對象慌植,在前臺開發(fā)中可以先調(diào)用這些數(shù)據(jù)燎竖,不用等待后臺接口完成彰居。
let http = require('http');
let url = require('url');
let fs = require('fs');
let server = http.createServer((req, res) => {
req.url = "car.json";
// var pathname = url.parse(req.url).pathname; //獲取url的pathname (/car.json)
fs.readFile(req.url, function (err, data) { //fs模塊加載文件
if (err) {
res.writeHead(404, {
'Content-Type': 'text/html'
});
} else {
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(data));
}
res.end();
});
});
server.listen(3000, '127.0.0.1', () => {
console.log("服務器已經(jīng)運行,請打開瀏覽,輸入:http://127.0.0.1:3000來進行訪問.")
});
或者增加不同的請求方式(get窜觉、post等等)的接口谷炸、不同響應消息體(json、xml等等)的接口禀挫、對安全有要求(如需要在http頭里加sessionid等等)的接口或是接口的特殊狀態(tài)(如有延遲旬陡,可以在server代碼里加一個setTimeout)