Nodejs搭建web服務器


Node搭建本地服務
根據demo文件夾位置,右鍵啟動命令窗口(shift+右鍵---在此處打開命令窗口),需是server.js文件夾路徑,在命令行node server啟動服務

檢測node版本及npm版本
命令行輸入:node -v
命令行輸入:npm -v
創建服務器,以及對應css和js文件的引入和判斷(不加判斷,會導致css/js不生效)
對css和js文件進行過濾,否則會導致‘Resource interpreted as Stylesheet but transferred with MIME type text/html’
文件夾新建server.js文件(啟動服務用的,監聽服務),代碼如下:

var http=require('http');
var fs = require('fs');
var url = require('url');
//創建服務器
http.createServer(function(request,response) {
  //解析請求,包括文件名
  var pathname= url.parse(request.url).pathname;
  //輸出請求的文件名
  console.log("Request for "+ pathname + "  received.");
//獲取后綴,判斷是js還是css文件,如果目錄結構不同,此處需要修改
  var firstDir = pathname && pathname.split('/')[1];
  var ContentType = {'Content-Type': 'text/html'};

  // js - application/x-javascript
  if (firstDir && firstDir === 'css') {
    ContentType = {'Content-Type': 'text/css'};
  } 
  if (firstDir && firstDir === 'js') {
    ContentType = {'Content-Type': 'application/x-javascript'}
  }

  //從文件系統中去請求的文件內容
  fs.readFile(pathname.substr(1),function(err, data) {
    if(err) {
      console.log(err);
      //HTTP 狀態碼 404 : NOT FOUND
      //Content Type:text/plain
      response.writeHead(404, {'Content-Type': 'text/html'});
    }
    else {
      //HTTP 狀態碼 200 : OK
      //Content Type:text/plain
      response.writeHead(200, ContentType);

      //寫會回相應內容
      response.write(data.toString());
    }
    //發送響應數據
    response.end();
  });
}).listen(8080);

console.log('Server running at http://127.0.0.1:8080/');    

如此,OK


免責聲明!

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



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