处理GET请求
get
请求url
:http://localhost:3000/?name=tom
// 1、引入express
const express = require('express')
// 2、创建app对象(项目对象)
const app = express()
// 3、处理请求
app.get('/',(req,res)=>{
//获取get请求的参数
console.log(req.query); //{ name: 'tom' }
res.end(`hello world`)
})
// 4、监听是否有请求
app.listen(3000,()=>{
console.log(`监听3000端口,服务启动!`);
})
处理POST请求
// 1、引入express
const express = require('express')
//引入body-parser来处理post请求的参数
const bodyParser = require('body-parser')
// 2、创建app对象(项目对象)
const app = express()
// 将body-parser添加到项目app中,把body-parser注册到app下
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json()) //解析JSON格式
// 3、处理请求
app.get('/',(req,res)=>{
console.log(req.query);
res.end(`hello world`)
})
//处理post请求,
app.post('/',(req,res)=>{
//打印post请求参数
console.log(req.body);
res.end(`post请求`)
})
// 4、监听是否有请求
app.listen(3000,()=>{
console.log(`监听3000端口,服务启动!`);
})
启动之后我这里使用postman
进行测试,就可以接收到post
请求的参数了。
路由拆分
新建路由文件,将app.js
中的代码拆分出来
在app.js
文件中引入passport.js
文件
art-template模板
- 首先需要安装
art-template
和express-art-template
yarn add express-art-template
yarn add art-template
- 配置
// 使用 express-art-template所需要的配置,
//引入express-art-template ,使用对应的html模板引擎,
app.engine('html',require('express-art-template'))
// 设置环境 production或者development
app.set('view options',{
debug:process.env.NODE_ENV !== 'production'
})
// 设置在哪一个目录下查找模板文件
app.set('views',path.join(__dirname,'views'))
//设置模板的后缀名为html
app.set('view engine','html')
后续我们可以返回整个html
模板
在index.html
文件中可以插入传递的数据,相关语法可以去查看文档