2015-06-01 32 views
-3

是否有辦法針對單一路線具有多種功能。快遞單路線,多功能

app.get('/r1', function(req, res) { 
    res.send('hello world 1'); 
}); 

app.get('/r1', function(req, res) { 
    res.send('hello world 2'); 
}); 

原因:內容協商,https://en.wikipedia.org/wiki/Content_negotiation我已經根據不同的範圍accept頭不同的模塊,所以我真的不能在路由器從一個接觸到其他。

請指教。

+0

'app.head( '/ R1',函數(.. )談判? – marekful

+0

不尋找頭,實際上,每個路由只需兩個不同的模塊調用, – user2727195

+0

[REST](http://en.wikipedia.org/wiki/Representational_state_transfer)呢?你不能真正擁有「2個具有相同名稱的函數」(將API端點視爲一個函數)。您應該檢查標題並根據該標題確定操作,但不能使用2個終結點。 –

回答

0

雖然你不能因爲你先描述每路線多種功能,你可以做內容協商路線內,

看沿

app.get('/r1', function(req, res) { 
    if(req.is('html')) { 
    //do your html stuff 
    return res.send('It was html') 
    } 

    if(req.is('json')) { 
    //do your json stuff 
    return res.send('It was json') 
    } 

    //wasn't html or json, so send a 406 
    res.status(406); 
    res.send('Content type not acceptable'); 
}); 
req.is(type) http://expressjs.com/api.html

東西

另外,有人已經做了上述的方便的小npm包: https://www.npmjs.com/package/express-negotiate

編輯

按照評論,res.format可以在接受頭一起使用: 請看看我以前的鏈接

app.get('/r1', function(req, res) { 

    res.format({ 
    'text/plain': function(){ 
     res.send('hey'); 
    }, 

    'text/html': function(){ 
     res.send('<p>hey</p>'); 
    }, 

    'application/json': function(){ 
     res.send({ message: 'hey' }); 
    }, 

    'default': function() { 
     // log the request and respond with 406 
     res.status(406).send('Not Acceptable'); 
    } 
    }); 
}); 
+0

你如何做自定義頭像談判'接受' – user2727195

+0

請閱讀我發佈的鏈接 - 搜索res.format – Alex

+0

編輯答案。也見這裏http://runnable.com/UTlPPF-f2W1TAAEb/content-negotiation-using-express-for-node-js – Alex