2016-03-18 61 views
0

我正在使用Node.js製作的API。 我正在使用express,Mongodb和我必須創建一個具有複雜數據結構的路由。複雜請求

這樣的:

{ 
    title: String, 
    description: String, 
    photo: Data Image, 
    list: [ 
    { 
    title: String, 
    photo: Data Image 
    }, 
    .... 
    ] 
} 

所以我有這樣的標題和描述的一些信息。 然後我有一張照片和對象列表,其中可以包含照片和標題。

所以我的問題是我如何設計我的路線爲這樣的要求?

我是否需要分開單獨上傳照片?

什麼是這樣的結構(服務器< - >客戶端)的最佳設計?

+0

你的問題似乎太板,你有一些代碼測試?或搜索一些示例代碼? – zangw

+0

不,我沒有,我的情況是非常具體的。我試圖找到通過API發送圖像的最佳做法。但問題是,我是否必須對整個數據執行單個請求或將其分開。我在這裏有點困惑。 – user2724028

+0

太板問題! –

回答

1

在您的客戶端,發送您的複雜數據結構作爲請求的主體。

您的路線可能是這樣的:

// POST /albums 
router.post('/', function(req, res, next) { 
    var album = req.body; //this is the data sent in the body of the request 
    // do whatever you want with 'album' 
}); 

在你app.js,包括:

app.use(require('body-parser').json()) // needed to parse the body to json format

app.use('/albums', require('./routes/albums')); // mount your route

普萊舍,請注意您應該把要求陳述o在文件頂部,在分離的變量上。

如果您想更新的相冊,你的路線應該是:

// PUT /albums/:id 
router.put('/:id', function(req, res, next) { 
    var albumId = req.params.id; // this is the id to update 
    var album = req.body; // this is the data sent in the body of the request 
    // do whatever you want with 'album' 
}); 
+0

感謝您的回答。聽起來不錯。 – user2724028