2012-01-12 86 views
1

越來越日期使用簡單的例子從URL和返回JSON

var server = http.createServer(function(req, res){ 
    var output = {message: "Hello World!"}; 
    var body = JSON.stringify(output); 

    res.writeHead(200, { 
    "Content-Type": "application/json", 
    "Access-Control-Allow-Origin": "*" 
    }); 
    res.end(body); 
}); 

我可以返回JSON對象。如何從這樣的請求中返回一些參數

url: http://localhost:8080/get/jhon 
output: {"message": "Hello jhon"} 

回答

1

添加一個檢查爲request.url

基本上,使用自己的代碼爲例:

var server = http.createServer(function(req, res){ 
    var output = {message: "Hello World!"}; 
    var body = JSON.stringify(output); 
    res.writeHead(200, { 
    "Content-Type": "application/json", 
    "Access-Control-Allow-Origin": "*"  
    }); 
    //.split creates an array with strings from the given url 
    //req.url -> gives everything that's right after the http://localhost:8080/ portion 
    var requested = req.url.split("/"); 
    output.message = "Hello " + requested[2]; // 0 is empty, 1 is "get" 
    res.end(output); 
}); 

希望有所幫助。

+1

找到更好的方法require('url')。parse(req.url) – coure2011 2012-01-12 18:00:37