Skip to content

Commit 34f8031

Browse files
committed
about http post raw data
1 parent 60bebed commit 34f8031

4 files changed

Lines changed: 65 additions & 0 deletions

File tree

doc/demo/day1/http/app.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,18 @@ var users = require('./routes/users');
1111
var app = express();
1212
var multer = require('multer')
1313

14+
// for raw data
15+
app.use(function(req, res, next){
16+
if (req.is('text/*')) {
17+
req.text = '';
18+
req.setEncoding('utf8');
19+
req.on('data', function(chunk){ req.text += chunk });
20+
req.on('end', next);
21+
} else {
22+
next();
23+
}
24+
});
25+
1426
app.use(multer({
1527
dest: './uploads/',
1628
rename: function (fieldname, filename) {
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>post-1 </title>
5+
<link rel='stylesheet' href='/stylesheets/style.css' />
6+
<script src='/javascripts/jquery.js'></script>
7+
</head>
8+
<body>
9+
<h1>Post with form-data</h1>
10+
<form method="post"action="/users/post/formdata" enctype="multipart/form-data">
11+
<input type="text" name="desc">
12+
<input type="file" name="pic">
13+
14+
<input type="submit" value="提交">
15+
<input type="reset" value="重置">
16+
</form>
17+
</body>
18+
</html>

doc/demo/day1/http/readme.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,36 @@ IMPORTANT: Multer will not process any form which is not multipart/form-data
6262
## Post with raw
6363

6464

65+
To get the raw body content of a request with Content-Type: "text/plain" into req.rawBody you can do:
66+
67+
https://gist.github.com/tj/3750227
68+
69+
70+
req.rawBody已经被干掉了,现在只能用req.text
71+
72+
下面是tj给出的代码片段
73+
74+
```
75+
var express = require('./')
76+
var app = express();
77+
78+
app.use(function(req, res, next){
79+
if (req.is('text/*')) {
80+
req.text = '';
81+
req.setEncoding('utf8');
82+
req.on('data', function(chunk){ req.text += chunk });
83+
req.on('end', next);
84+
} else {
85+
next();
86+
}
87+
});
88+
89+
app.post('/', function(req, res){
90+
res.send('got "' + req.text + '"');
91+
});
92+
93+
app.listen(3000)
94+
```
6595

6696

6797
## node express upgrade

doc/demo/day1/http/routes/users.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,10 @@ router.post('/post/formdata', function(req, res) {
1818
res.json(req.body);
1919
});
2020

21+
router.post('/post/raw', function(req, res) {
22+
// res.send('respond with a resource');
23+
res.json(req.text);
24+
});
25+
2126

2227
module.exports = router;

0 commit comments

Comments
 (0)