文章目錄
  1. 在index.html的目錄建立server.js
  2. 輸入server.js內容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    var http = require('http');
    var fs = require('fs');
    //404 response
    function sent404Response(response){
    response.writeHead(404,{"Context-Type":"text/plain"});
    response.write('Error 404:Page not found!'); //write a response to the client
    response.end(); //end the response
    }
    //handle a user request function
    function onRequest(req, res) {
    /*
    console.log("A user made a request "+ req.url);
    res.writeHead(200,{"Context-Type":"text/plain"});
    res.write('Here is some data.'); //write a response to the client
    res.end(); //end the response
    */
    if (req.method == 'GET' && req.url == '/') {
    res.writeHead(200,{"Context-Type":"text/plain"});
    fs.createReadStream("./index.html").pipe(res);//將"./index.html"傳入res參數內
    }else{
    sent404Response(res);
    }
    }
    //create a server object:
    http.createServer(onRequest).listen(8888); //the server object listens on port 8080
    console.log("Server is now running.")
  3. 執行server.js node server.js

  4. 其實最簡單的方式就是安裝http-server模組。

    1
    npm i -g http-server
  5. 執行http-server即可。

文章目錄