2013-10-18 35 views
0

我是Node.js的新手。我正在嘗試創建一個Web服務器,它將1)提供靜態html網頁,2)提供基本的JSON/REST API。我的管理層告訴我必須使用RESTIFY(我不知道爲什麼)。目前,我有以下幾點:無法使用RESTIFY從REST API返回JSON

var restify = require('restify'); 
var fs = require('fs'); 
var mime = require('mime'); 
var ecstatic = require('ecstatic'); 

var ws = restify.createServer({ 
    name: 'site', 
    version: '0.2.0' 
}); 

ws.use(restify.acceptParser(server.acceptable)); 
ws.use(restify.queryParser()); 
ws.use(restify.bodyParser()); 
ws.use(ecstatic({ root: __dirname + '/' })); 

ws.get('/rest/customers', findCustomers); 

ws.get('/', ecstatic({ root:__dirname })); 
ws.get(/^\/([a-zA-0-9_\.~-]+\/(.*)/, ecstatic({ root:__dirname })); 

server.listen(90, function() { 
    console.log('%s running on %s', server.name, server.url); 
}); 

function findCustomers() { 
    var customers = [ 
    { name: 'Felix Jones', gender:'M' }, 
    { name: 'Sam Wilson', gender:'M' }, 
    { name: 'Bridget Fonda', gender:'F'} 
    ]; 
    return customers; 
} 

我啓動Web服務器之後,我嘗試訪問我的瀏覽器http://localhost:90/rest/customers/的請求。然而,它只是坐在那裏,我似乎從來沒有得到迴應。我使用Fiddler來監視流量,結果很長一段時間保持爲' - '。

如何從這種類型的REST調用返回一些JSON?

謝謝

回答

3

從未與ecstatic的工作,但我不認爲你需要對靜態內容的文件服務器,因爲你運行的RESTify和返回JSON。

你沒有得到迴應,因爲你不res.send

下面的代碼終止看起來不錯

ws.get('/rest/customers', findCustomers);

但試圖改變findCustomers功能這樣

function findCustomers(req,res,next) { 
    var customers = [ 
    { name: 'Felix Jones', gender:'M' }, 
    { name: 'Sam Wilson', gender:'M' }, 
    { name: 'Bridget Fonda', gender:'F'} 
    ]; 
res.send(200,JSON.stringify(customers)); 
} 
+7

或者只是'res.send(customers)'。 – robertklep

2

在2017年,現代化的做法是:

server.get('/rest/customer', (req,res) => { 
    let customer = { 
    data: 'sample value' 
    }; 

    res.json(customer); 
});