问题
When I send a PUT request to my express server, req.body sometimes has a __proto__ property, and other times not.
Using node 0.10.26 and express 3.2.3:
- When I put
{"a":"b", "__proto__": {}}, - Then
req.bodyis{"a":"b"}
Using node 4.1.0 and express 3.2.3:
- When I put
{"a":"b", "__proto__": {}}, - Then
req.bodyis{"a":"b", "__proto__": {}}
So newer versions of node do not strip the __proto__ property. I actually liked this behaviour; now I have to write my own middleware which strips away the property. I think this has something to do with bodyparser. The weird thing is, though, that both tests have the same version of express (and hence the same version of bodyparser).
Can anyone give any motivation as to why this was changed? What is the recommended way of resolving this?
回答1:
Neither express nor node are responsible for this behavior. This has actually been changed a long time ago in V8, for compatibility and spec conformance.
Old behavior (
__proto__is stripped):> var x = JSON.parse('{"__proto__":[]}'); > x.hasOwnProperty('__proto__'); falseNew behavior (
__proto__is not stripped):> var x = JSON.parse('{"__proto__":[]}'); > x.hasOwnProperty('__proto__'); true
Sources :
- https://code.google.com/p/chromium/issues/detail?id=115055
- https://code.google.com/p/v8/issues/detail?id=1310
Solution:
Like you said, you can write a simple middleware to strip the property yourself:
function stripProto(req, res, next) {
delete req.body.__proto__;
next();
}
// ...
app.use(stripProto);
来源:https://stackoverflow.com/questions/34003275/why-dont-newer-versions-of-node-remove-proto-from-request-body