2015-01-15 26 views
0

我找到了Difference between put and patch。我在閱讀之後明白了差異。它仍然朦朧。爲什麼angular-fullstack使用put和patch請求來表達?

我的問題是: 爲什麼約曼發電機:angular fullstack使用

router.put('/:id', controller.update); 
AND 
router.patch('/:id', controller.update); 

在有index.js他們server.collections的文件?

兩者的目的是什麼?此外,我將如何使用一個和另一個?

'use strict'; 

var express = require('express'); 
var controller = require('./thing.controller'); 

var router = express.Router(); 

router.get('/', controller.index); 
router.get('/:id', controller.show); 
router.post('/', controller.create); 
router.put('/:id', controller.update); 
router.patch('/:id', controller.update); 
router.delete('/:id', controller.destroy); 

module.exports = router; 

服務器控制器

// Updates an existing thing in the DB. 
exports.update = function(req, res) { 
    if(req.body._id) { delete req.body._id; } 
    Thing.findById(req.params.id, function (err, thing) { 
    if (err) { return handleError(res, err); } 
    if(!thing) { return res.send(404); } 
    var updated = _.merge(thing, req.body); 
    updated.save(function (err) { 
     if (err) { return handleError(res, err); } 
     return res.json(200, thing); 
    }); 
    }); 
}; 

回答

1

他們只是不同的HTTP動詞。閱讀https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods

PUT 
Requests that the enclosed entity be stored under the supplied URI. If the URI refers 
to an already existing resource, it is modified; if the URI does not point to an existing 
resource, then the server can create the resource with that URI.[15] 

PATCH 
Applies partial modifications to a resource.[18] 
+0

我很好奇補丁如何知道如何部分修改資源?前端的PUT和PATCH就像標誌,我假設。如果我猜測,這是因爲服務器技術知道如何處理這些標誌並採取相應的行動。由於我一起使用express + mongo,所以這些技術知道如何處理PATCH標誌。那是對的嗎? –

0

他們should'n是一樣的!

但我看到兩種方法在angular-fullstack上沒有區別,對我而言,它是錯誤

  • PUT - 更新整個實體,這意味着您需要發送每件物品的單個屬性,否則它們將被刪除。
  • 修補程序 - 部分更新,您可能只發送您想要更改的字段,其他將保留在服務器上。

如: 想象一下下面的實體:

car: { 
    color: red, 
    year: 2000 
} 

現在想象你發送一個補丁是這樣的:

{color: blue} 

實體現在是這樣的:

car: { 
    color: blue, // CHANGED 
    year: 2000 
} 

但相反,如果你發送了一個實體守ld是這樣的:

car: { 
    color: blue // CHANGED 
    year: null // May be null, undefined, removed, etc... 
} 
+0

似乎補丁總是更靈活。出於什麼原因你會使用PUT。 PATCH更昂貴(懷疑它很重要),但似乎沒有理由使用PUT。 –

+1

我同意。使用PATCH或事件POST而不是PUT。 但是...有一個由框架生成的放置請求,它不尊重restfull規則。我的意見是他們應該刪除PUT或使其作爲RESTFUL規範工作。 – barata