express框架简单封装了node的http模块,因此,express支持node原生的写法。express的重要意义在于:支持使用中间件 + 路由 来开发web服务器逻辑。
//使用http模块
const http = require("http");
let server = http.createServer(function (req, res) {
// 服务器给浏览器回应消息
res.end("hello browser");
});
server.listen(8090);
// 使用express
const app = require('express')()
const http = require('http').Server(app)
app.get('/', (req, res) => {
res.send('hello world')
})
http.listen(8090, () => {
console.log('服务器启动成功')
})
express 是一个简洁而灵活的 node.js Web应用框架,提供了一系列强大的特性帮助我们创建各种 Web 应用,并提供了丰富的 HTTP 工具,使用 express 可以快速地搭建一个功能完整的网站。
express 框架核心特性:
可以设置中间件(app.use())来响应 HTTP 请求;
定义了路由表用于执行不同的 HTTP 请求动作;
可以通过向模板传递参数来动态渲染 HTML 页面。