2016-06-30 25 views
0

我是新來的Node JS,並試圖創建自己的Web服務器來託管我的Linux服務器(Raspberry Pi)上非常基本的網站。以下代碼顯示index.html,但不顯示users.html文件。請指出我在做什麼錯了..我在這個文件夾中都有index.html和users.html文件。 (旁註:我知道這樣的CSS &還沒有實現;我只是在編寫這個web服務器的開始)。爲什麼我的節點js webserver不能用於額外的頁面?

var http = require('http'); 
var fs = require('fs'); 

//404 response 
function send404Response(response){ 
     response.writeHead(404, {"Content-Type": "text/plain"}); 
     response.write("Error 404: Page not found!"); 
     response.end(); 
} 

//Handles user request 
function onRequest(request, response){ 
     if(request.method == 'GET' && request.url == '/'){ 
       response.writeHead(200, {"Content-Type": "text/html"}); 
       fs.createReadStream("./index.html").pipe(response); 
     }else if(request.method == 'Get' && request.url == '/users'){ 
       response.writeHead(200, {"Content-Type": "text/html"}); 
       fs.createReadStream("./users.html").pipe(response); 
     } 
     else{ 
       send404Response(response); 
     } 
} 

http.createServer(onRequest).listen(8884); 
console.log("Server is running..."); 
+0

'request.method =='Get'' - 應該在所有大寫的「GET」中。 – brandonscript

回答

0

您在第二個if語句中有拼寫錯誤。

else if(request.method == 'Get' && request.url == '/users'){ 

應改爲

else if(request.method == 'GET' && request.url == '/users'){ 

HTTP方法總是大寫,你是服務器看到了 「GET」 方法。該URL與第一個IF語句不匹配,並且該方法在第二個語句中不匹配,所以它落在了else之後並且找不到404。

相關問題