2016-03-18 66 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