Express项目的创建和初步使用

Express

1、初始化

​ 生成package.json文件 【npm init】

​ 安装express,使用命令【npm install express】

2、修改完代码自动启动

​ 第三方工具【nodemon】,基于nodejs开发的第三方命令行工具,使用的时候需要独立安装

​ npm install nodemon -g

​ node xxx.js 启动 ——> nodemon xxx.js

// 1、引入express
const express = require('express')

// 2、创建服务器应用程序
// 原生的http.createServer
const app = express()

// 当服务器接收到get请求/的时候,执行回调
app.get('/', function(req, res) {
    res.send('hello express')
})

app.get('/hello', function(req, res) {
    res.send('你好 express')
})

app.listen(3000, function() {
    console.log('项目启动了:127.0.0.1:3000')
})

3、添加路由

app.get('/hello', function(req, res) {
    res.send('你好 express')
})

app.post('/hello', function(req, res) {
    res.send('你好 express')
})

4、处理静态文件

// 公开执行目录,这时候我们可以通过/public/xx 去访问public目录下的文件
// 如果请求路径包含/public/ 查找./public/下的文件
// http://127.0.0.1:3000/public/img/girl.jpg 访问public/img/girl.jpg图片
app.use('/public/',express.static('./public/'))

// 第一个参数不写,默认为'/'
// http://127.0.0.1:3000/img/girl.jpg 访问public/img/girl.jpg图片
app.use(express.static('./public/'))

5、在express中使用art-template

​ 安装

npm install --save art-template
npm install --save express-art-template
// 配置art-template模板
// 第一个参数,当渲染以.html文件的时候,使用art-template模板引擎
// express-art-template把模板整合到express
app.engine('html', require('express-art-template'));

// express为response响应对象 提供了一个render方法
// render默认是不能使用的,但是如果配置了模板引擎就可以使用
// 第一个参数不用写路径,默认去文件夹【views】查找文件
// app.set('views', '路径') 修改默认的views
app.get('/', function (req, res) {
  res.render('index.html')
})

// 访问views/user/index.html文件
//app.get('/user', function (req, res) {
//  res.render('user/index.html')
//})

// 添加数据 显示参数
app.get('/user', function(req, res) {
  res.render('user/index.html', {
    user: {
      name: '张三',
      age: 20
    }
  })
})

6、获取请求数据

​ get

​ req.query获取

	app.get('/liuyan', function(req, res) {
  	const query = req.query
 	console.log(query)
  	query.date = '2020-01-01'
 	msgs.push(query)
 	// 重定向
 	res.redirect('/')
}

​ post
​ express没有内置的API获取post参数,使用中间件body-parser
​ req.body获取

在express中使用art-template

​ 安装

npm i body-parser -s
const bodyParser = require('body-parser')
//使用body-parser
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())

// req.body获得数据
app.post('/liuyan', function(req, res) {
  const body = req.body
  body.date = '2020-01-01'
  msgs.push(body)
  res.redirect('/')
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值