【问题标题】:RESTful web service url html vs jsonRESTful Web 服务 url html vs json
【发布时间】:2014-09-01 12:05:01
【问题描述】:
为了为客户生成访问数据的url,我遵循规范:
- 通过以下 URL 提供与客户有关的所有 JSON 数据:www.somesite.com/customers
- 要创建、更新或删除,请使用带有适当动词的 www.somesite.com/customers/ url,分别为 POST、PUT 和 DEL
但是,我还想提供一个 html 页面(最好在 www.somesite.com/customers 上),它通过 AJAX 调用访问所有 JSON 数据。
我是否应该根据请求中的标头使用 HTML 或 JSON 在相同的 url (www.somesite.com/customers) 进行响应?或者有更好/标准的方法吗?
【问题讨论】:
标签:
json
node.js
web-services
rest
【解决方案1】:
使用标题很难处理。 Imo 最好只为 api 使用可预测的不同 url。如:
- www.somesite.com/customers.json
- api.somesite.com/customers
- www.somesite.com/api/customers
- www.somesite.com/api/v1/customers
【解决方案2】:
根据 REST 原则,URL 表示资源,响应是资源的表示。
您可以根据客户端指定的条件为同一资源生成不同的表示形式(JSON 或 HTML)。这可以通过 Accept 标头项或 Query 字符串指定。
【解决方案3】:
有可能。
如果是xhr-Request,您可以查看请求的内部。在 express.js 中,它位于“req.xhr”。取决于您是否可以交付 HTML 或 JSON。
app.get('/customers', function(req, res){
if(req.xhr){
res.type('application/json');
res.send({});
}else{
res.type('text/html');
res.send('<html>...</html>');
}
});