2013-07-20 84 views
4

我試圖做一個簡單的窗體,用戶名和姓氏,當用戶提交信息時,顯示另一個頁面。我在html中做了一個表單,但我不確定接下來要做什麼?是否有人使用node js的小型自包含表單的示例?簡單的窗體節點js應用程序

+0

github上有很多例子,例如[看看這個](https://github.com/madhums/node-express-mongoose-demo)。 –

回答

7

這個例子並不完全完成你的任務。但它是一個獨立的node.js程序,它在收到表單時顯示一個表單和一個不同的頁面。

將其複製到文件中,然後運行node filename.js,然後在瀏覽器中轉到http://localhost:3000

注意異步代碼結構。我定義了一個handler函數,但不要立即執行它。我們將功能傳遞給http.createServer,然後撥打.listen(3000)。現在,當HTTP請求進入時,http服務器會將req, res對傳遞給處理函數。 req是請求對象(這將包含表單數據;請參閱this question以獲取有關如何獲取數據的提示)(我建議您直接進入並構建一個小型Express應用程序,這是一個非常好的框架。)

//app.js 
// Load the built in 'http' library 
var http = require('http'); 
var util = require('util'); 

// Create a function to handle every HTTP request 
function handler(req, res){ 
    if(req.method == "GET"){ 
    console.log('get'); 
    res.setHeader('Content-Type', 'text/html'); 
    res.writeHead(200); 
    res.end("<html><body><form action='/' method='post'><input type='text' name='hello'><input type='submit'></form></body></html>"); 
    } else if(req.method == 'POST'){ 
    console.log('post'); 
    // Here you could use a library to extract the form content 
    // The Express.js web framework helpfully does just that 
    // For simplicity's sake we will always respond with 'hello world' here 
    // var hello = req.body.hello; 
    var hello = 'world'; 
    res.setHeader('Content-Type', 'text/html'); 
    res.writeHead(200); 
    res.end("<html><body><h1>Hello "+hello+"!</h1></body></html>"); 
    } else { 
    res.writeHead(200); 
    res.end(); 
    }; 
}; 

// Create a server that invokes the `handler` function upon receiving a request 
// And have that server start listening for HTTP requests 
// The callback function is executed at some time in the future, when the server 
// is done with its long-running task (setting up the network and port etc) 
http.createServer(handler).listen(3000, function(err){ 
    if(err){ 
    console.log('Error starting http server'); 
    } else { 
    console.log('Server listening on port 3000'); 
    }; 
});