簡單的nodejs http-server httpserver


直接安裝 http-server :
npm install http-server -g
加參數-g就可以在任何目錄啟動:
http-server . --port 80


自己寫:

var http = require('http');
http.createServer(function (request, response) {
     // 發送 HTTP 頭部  // HTTP 狀態值: 200 : OK // 內容類型: text/plain 
    response.writeHead(200, {'Content-Type': 'text/plain'}); 
    // 發送響應數據 "Hello World" 
    response.end('Hello World\n');
}).listen(8888);
// 終端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

運行:

node main.js
Server running at http://127.0.0.1:8888/

順別提一下,使用supervisor自動監控文件變化,可以自動重啟。

npm i -g supervisor 
supervisor test.js
解決 supervisor : 無法加載文件 C:\Users\charles\AppData\Roaming\npm\supervisor.ps1
在使用vsCode中運行cnpm install時報錯。
解決方法
1.在win10 系統中搜索框 輸入 Windows PowerShell,選擇 管理員身份運行

2、使用,win+R打開了powershell命令行之后,輸入set-ExecutionPolicy RemoteSigned,然后更改權限為A,最后通過 get-ExecutionPolicy 查看當前的狀態

 

可以讀取本地文件,從httpserver返回的示例:
var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
if (req.url === '/serverRedirect') {
res.statusCode
= 301;
res.setHeader(
'Location', 'http://' + req.rawHeaders[1]);
res.end();
}
else if (req.url === '/downPdf') {
res.writeHead(
200, { 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment;filename=test.pdf' });
res.end(
'Hello World\n');
}
else if (req.url === '/viewPdf') {

    fs.readFile(</span>'d:/sample.pdf', (err, data) =&gt;<span style="color: #000000;"> {
        console.log(</span>"read success."<span style="color: #000000;">)
        res.writeHead(</span>200<span style="color: #000000;">, {
            </span>'Content-Type': 'application/pdf; charset=utf-8'<span style="color: #000000;">,
            </span>'Content-Disposition': 'inline;filename=test.pdf'<span style="color: #000000;">,
            </span>"Access-Control-Allow-Origin": "*"<span style="color: #000000;">,
            </span>"Access-Control-Allow-Headers": "X-Requested-With"<span style="color: #000000;">
        });
        </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (err) {
            res.write(</span>'Server error:' +<span style="color: #000000;"> err);
        } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
            console.log(</span>"read success."<span style="color: #000000;">)
            res.write(data);
        }
        res.end();
    })

} </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
    res.setHeader(</span>'Custom', ['Header'<span style="color: #000000;">]);
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 發送 HTTP 頭部  // HTTP 狀態值: 200 : OK // 內容類型: text/plain </span>
    res.writeHead(200, { 'Content-Type': 'text/plain'<span style="color: #000000;"> });
    let content </span>=<span style="color: #000000;"> req.url;
    </span><span style="color: #0000ff;">if</span> (req.headers.accept === '*/*;test/header'<span style="color: #000000;">) {
        content </span>+= 'header/received'<span style="color: #000000;">;
    }
    </span><span style="color: #0000ff;">if</span> (req.headers.origin === 'http://new-origin'<span style="color: #000000;">) {
        content </span>+= 'new/origin'<span style="color: #000000;">;
    }
    res.end(content);
}

}).listen(8888);
// 終端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

 


header上不能加入中文
      let nonUtf8Str=Buffer.from([0xcc, 0xec]);
      res.setHeader('Content-Disposition', [ Buffer.concat([ Buffer.from(' attachment; filename='),nonUtf8Str]).toString() ]);

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM