`

Express Get和Post获取参数

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2354503

 

Project Directory

 

npm install express


 

npm install body-parser

Note:post提交需要这个body-parser来获取参数 

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>express get & post</title>
</head>
<body>
	<form action="/testget" method="get">
		<label for="username">username:</label><input type="text" name="username"><br>
		<label for="password">password:</label><input type="password" name="password"><br>
		<input type="submit" value="test-get">
	</form>

	<hr>

	<form action="/testpost" method="post">
		<label for="username">username:</label><input type="text" name="username"><br>
		<label for="password">password:</label><input type="password" name="password"><br>
		<input type="submit" value="test-post">
	</form>
</body>
</html>

 

index.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var urlencodedParser = bodyParser.urlencoded({
	extended: false
});

app.use(bodyParser.urlencoded({
	extended: false
}));

app.get('/', function(req, res) {
	res.sendFile(__dirname + "/index.html");
});

app.get('/testget', function(req, res) {
	// http://localhost:8888/testget?username=hello&password=world
	var username = req.query.username;
	var password = req.query.password;

	console.log(username);
	console.log(password);

	res.send('Hello Get');
});

app.post('/testpost', function(req, res) {
	// http://localhost:8888/testpost
	var username = req.body.username;
	var password = req.body.password;

	console.log(username);
	console.log(password);

	res.send('Hello Post');
});

app.listen(8888, function() {
	console.log('listening on port 8888');
});

 

Run

test-get,username:hello, password:world

查看Browser


 

查看Console


 

test-post,username:sky, password:funny

查看Browser 


查看Console


 

 

 

 

  • 大小: 8.3 KB
  • 大小: 44.9 KB
  • 大小: 26.1 KB
  • 大小: 17.1 KB
  • 大小: 11.6 KB
  • 大小: 16.7 KB
  • 大小: 17 KB
  • 大小: 9.5 KB
  • 大小: 22.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics