Node Express 初探

时间:2022-05-05 09:55:58

一如既往,先上一张图

Node Express 初探

Express 基于 Node.js 平台,快速、开放、极简的 web 开发框架。

关于Express更多相关知识请链接至官网http://www.expressjs.com.cn/

1、访问本地服务

在指定的目录中创建app.js

 //express
var express = require('express');
//app核心
var app = express();
//get
app.get('/', function (req, res) {
res.send('Node express 初试探....!');
});
//访问端口
var server = app.listen(, function (req,res,next) {
var host = server.address().address;
var port = server.address().port;
console.log(host);

node 启动app.js文件,浏览器端输入localhost:1314 即可访问响应内容 Node Express 初探.....

2.实现浏览器端url参数路由跳转

 //express
var express = require('express');
var app = express(); //express.static 设置静态资源(images/js/css等)文件目录
app.use(express.static('public')); //get请求 根据url实现路由跳转
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + '/' + 'index.html');
}); //get请求 根据url实现路由跳转 c
app.get('/login.html', function (req, res) {
res.sendFile(__dirname + '/' + 'login.html');
});
//端口
var server = app.listen(1314, function () {
var host = server.address().address;
var port = server.address().port;
console.log("实例应用,访问地址为 http://%s:%s", host, port);
})

inde.html 主页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Node Express路由跳转</title>
</head>
<body>
<p>实现Express路由跳转......</p>
</body>
</html>

login登录页面

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Node Express路由跳转</title>
</head>
<body>
<form action="" method="GET">
姓名:<input type="text" name="username"><br/>
密码:<input type="password" name="pass"></br>
<input type='submit' value='提交'/>
</form>
</body>
</html>

3、get提交

//提交表单数据
app.get('/app_get', function (req, res) {
// 输出json格式
// 将接收的数据转换为json格式输出
response = {
username : req.query.username,
pass : req.query.pass,
};
console.log(response);
res.end(JSON.stringify(response));
});

设置form属性 <form action="http:///localhost:1314/app_get" method="GET"></form> 即可,响应数据是字符串对象

4、post提交

 var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({
extended : false
});
app.use(express.static('public'));
app.get('/post.html', function (req, res) {
res.sendFile(__dirname + '/' + 'post.html');
});
app.post('/app_post', urlencodedParser, function (req, res) {
// JSON 格式
response = {
username : req.body.username,
pass : req.body.pass,
}; console.log(response);
res.end(JSON.stringify(response));
});
var server = app.listen(1314, function () {
var host = server.address().address;
var port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port);
})

设置form属性 <form action="http:///localhost:1314/app_post" method="post"></form> 即可