10.Express.js
JS基础¶
学习js资料推荐
https://eloquentjavascript.net/
Hello, World¶
nodejs官网:https://nodejs.org/en/about
const http = require('node:http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
node hello.js
Server running at http://127.0.0.1:3000/
Express.js¶
Express.js是node.js里面的一个后端框架
初始化项目
npm init
或者
npm init -y
Wrote to D:\Workplace\web3.0\Demo\expressjs\express-cbi02\package.json:
{
"name": "express-cbi02",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
安装express
npm install express --save
package.json中补充了dependency
NFT交易市场后端设计¶
接收用户图片,把用户图片上传IPFS,处理返回的hash
添加路由¶
// app.js
const express=require('express')
const app=express()
app.get('/',function (req,res){
res.send("Hello, World")
})
app.listen(3000)
启动
node app.js
添加GET路由¶
代码
const products=[
{
"name":"Television",
"price":2000,
"brand":"xiaomi"
},
{
"name":"Laptop",
"price":5000,
"brand":"Lenovo"
},
]
app.get('/products/:brand',(req,res)=>{
const brand=req.params.brand;
console.log(brand)
const filteredProducts=products.filter(product=>product.brand===brand);
res.send(filteredProducts)
})
请求
http://127.0.0.1:3000/products/xiaomi
返回
[{"name":"Television","price":2000,"brand":"xiaomi"}]
添加POST路由¶
app.use(express.json())
app.post('/products',(req,res)=>{
const name=req.body.name;
const price=req.body.price;
const brand=req.body.brand;
products.push({name,price,brand});//nodejs特性,转json加进来
res.json({
"message":"New product created",
"data":products
})
})
postman测试
{
"message": "New product created",
"data": [
{
"name": "Television",
"price": 2000,
"brand": "xiaomi"
},
{
"name": "Laptop",
"price": 5000,
"brand": "Lenovo"
},
{
"name": "Car",
"price": 10000,
"brand": "Geely"
}
]
}
使用中间键处理相关请求¶
所有路由都会调用它
可以具体定制哪些路由使用
const requestUrlLogger=(req,res,next)=>{
console.log('url is: ',req.url);
next();
}
app.use(requestUrlLogger)
使用模板引擎¶
模板引擎pug
安装
npm install pug
//home.pug
html
head
title =title
body
h1=message
div
p Welcome to #{title}
// 模板引擎
app.set('view engine','pug')
app.set('views','./views')
app.get('/home',(req,res)=>{
res.render('home',{
title:'Home',
message:'Hello there'
})
})
postman测试
请求
localhost:3000/home
返回
<html>
<head>
<title>=title </title>
</head>
<body>
<h1>Hello there</h1>
<div>
<p>Welcome to Home</p>
</div>
</body>
</html>
nodemon¶
监听文件的每一个改变,自动重启
npm install --save-dev nodemon
nodemon app.js
// 如果找不到nodemon
./node_modules/nodemon/bin/nodemon.js app.js
每次都./node_modules/nodemon/bin/nodemon.js app.js太麻烦---》写到package.json里面的scripts
{
"main": "app.js",
"scripts": {
"start":"nodemon app.js"
},
启动
npm run start
完整代码¶
const express=require('express')
const app=express()
// 中间件
const requestUrlLogger=(req,res,next)=>{
console.log('url is: ',req.url);
next();
}
app.use(requestUrlLogger)
app.use(express.json())
app.get('/',function (req,res){
res.send("Hello, World")
})
// 模板引擎
app.set('view engine','pug')
app.set('views','./views')
app.get('/home',(req,res)=>{
res.render('home',{
title:'Home',
message:'Hello there'
})
})
// 模拟数据
const products=[
{
"name":"Television",
"price":2000,
"brand":"xiaomi"
},
{
"name":"Laptop",
"price":5000,
"brand":"Lenovo"
},
]
app.get('/products/:brand',(req,res)=>{
const brand=req.params.brand;
const filteredProducts=products.filter(product=>product.brand===brand);
res.send(filteredProducts)
})
app.post('/products',(req,res)=>{
const name=req.body.name;
const price=req.body.price;
const brand=req.body.brand;
products.push({name,price,brand});//nodejs特性,转json加进来
res.json({
"message":"New product created",
"data":products
})
})
const port=3000;
app.listen(port,()=>{
console.log(`Server is running on ${port}..`)
})