nodejs之express学习(1)

安装

npm i express

使用

// 导入
const express = require('express')
// 创建应用
const app = express()
// 创建路由
app.get('/home',(req,res)=>{
	res.end("hello express")
})
app.listen(3000,()=>{
	console.log("服务已启动~")
})

路由的介绍

什么是路由

官方定义:路由确定了应用程序如何响应客户端对特定端点的请求

路由的使用

一个路由的组成有 请求方法 , 路径 和 回调数 组成
express 中提供了一系列方法,可以很方便的使用路由,使用格式如下

app.<method>(path,callback)

在这里插入图片描述

获取请求参数

express框架封装了一些API来方便获取请求报文中的数据,并且兼容原生HTTP模块的获取方式

// 导入
const express = require('express')
// 创建应用
const app = express()
// 创建路由
app.get('/home',(req,res)=>{
	//原生操作
	console.log(req.method)   //get
	console.log(req.url)      
	console.log(req.httpVersion)
	console.log(req.headers)
	//express操作
	console.log(req.path)   // /home
	console.log(req.query)  // {a:'100',b:'200'}
	console.log(req.ip)     // 127.0.0.1
	//获取请求头
	console.log(req.get('host'))
	res.end("hello express")
})
app.listen(3000,()=>{
	console.log("服务已启动~")
})

路由参数获取

const express = require('express')
const app = express()
app.get('/:id.html',(req,res)=>{
	// get params  of url
	console.log(req.params.id)
	res.setHeader('content-type','text/html;charset=utf-8')
	res.send('details of goods')
})
app.listen(3000,()=>{
	console.log('server start')
})

练习

const express = require('express')
const {singers} = require('./singer.json')
const app = express()
app.get('/singer/:id.html',(req,res)=>{
	let {id} = req.params
	let result = singers.find(item=>{
		if(item.id===Number(id)){
			return true
		}
	})
	if(!result){
		res.end('404 Not Found')
		return
	}
	res.end(`
		<h1>${result.singer_name}</h1>
		<img src = '${result.singer_pic}'/>
	`)
})

app.listen(3000,()=>{
	console.log('server start')
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值