什么是 Express ?
Express 是一个基于 NodeJS 的 Web Server 开发框架,能够帮助我们快速的搭建 Web 服务器
为什么需要 Express ?
1、不使用框架,使用原生的 NodeJS 开发 Web 服务器,我们需要处理很多繁琐且没有技术含量的内容,例如:获取路由,处理路由等等
2、 不使用框架,使用原生的 NodeJS 开发 Web 服务器,需要解析 get、post 参数解析,使用 Express 可以使用现成的插件实现上面的功能,只要关心核心的业务逻辑即可
3、Python 中的 execjs 库已经停止更新,存在很多未知 bug,使用 express 不管从性能上还是易用性上都要高出一筹
如何使用 Express ?
手动安装
npm install express
简单使用
const express = require("express")
const app = express()
app.get('/',function(req,res){
res.send('hello,express')
})
app.listen(3000,()=>{
console.log("监听端口3000成功")
})
返回静态资源
const express = require("express")
const path = require("path")
const app = express()
app.get('/',function(req,res){
res.send('hello,express')
})
// 这里的 pathname 是存放静态资源的路径
app.use(express.static(path.join(__dirname,'pathname')));
app.listen(3000,()=>{
console.log("监听端口3000成功")
})
获取 get 请求参数
const express = require("express")
const app = express()
app.get('/',function(req,res){
res.send(req.query)
})
app.listen(3000,()=>{
console.log("监听端口3000成功")
})