express模块
一、创建web服务器
先下载express模块:npm install express
然后引入express模块
//引入express模块
const express=require('express');
//创建web服务器
const app=express();
//设置端口
app.listen(8080,()=>{
console.log('服务器创建成功');
})
二、路由
路由根据请求的方法和请求的URL作出特定的响应,是一个独立的方法
路由三要素:请求的方法、请求的URL、回调函数
1、res 响应的对象
(1)res.send()
res.send()
设置响应的内容并发送
//引入express模块
const express=require('express');
console.log(express);
//创建web服务器
const app=express();
//设置端口
app.listen(8080,()=>{
console.log('服务器创建成功');
})
//添加路由
//请求的方法:get 请求的URL:/index
//res.send() 设置响应的内容并发送
app.get('/index',(req,res)=>{
//设置响应的的内容并发送
res.send('hello world');
})
(2)res.redirect()
res.redirect()
设置跳转的URL并发送
//引入express模块
const express=require('express');
console.log(express);
//创建web服务器
const app=express();
//设置端口
app.listen(8080,()=>{
console.log('服务器创建成功');
})
//添加路由
//请求的方法:get 请求的URL:/index
//res.redirect() 设置跳转的URL并发送
app.get('/index',(req,res)=>{
res.redirect('https://www.w3school.com.cn/');
})
(3)res.sendFile()
res.sendFile()
设置响应的文件并发送,文件必须使用绝对路径(__dirname)
//引入express模块
const express=require('express');
// console.log(express);
//创建web服务器
const app=express();
//设置端口
app.listen(8080,()=>{
console.log('服务器创建成功');
})
//添加路由
//请求的方法:get 请求的URL:/index
// res.sendFile() 设置响应的文件并发送,文件必须使用绝对路径(__dirname)
app.get('/index',(req,res)=>{
res.sendFile(__dirname+'/1.html');
})
2、req 请求的对象
(1)req.url ()
req.url()
获取请求的URL
(2)req.method()
req.method()
获取请求的方法
(3)req.query()
req.query()
获取get传递的数据(查询字符串),结果为对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!---
method: 请求的方法
action:请求的url
-->
<form action="/mysearch" method="get">
<h2>用户搜索</h2>
<!-- 这个name起名字,是获取保存用户输入的值,传入服务器端-->
<input type="text" name="keyword">
<input type="submit">
</form>
</body>
</html>
//引入express模块
const express=require('express');
//创建web服务器
const app=express();
//设置端口
app.listen(8080,()=>{
console.log('服务器创建成功');
})
//路由(get/search),响应文件search.html,添加search.html页面
app.get('/search',(req,res)=>{
//响应文件search.html
res.sendFile(__dirname+'/search.html');
})
//点击提交按钮添加对应search.html的路由(get/mysearch),响应'搜索成功'
app.get('/mysearch',(req,res)=>{
//通过name获取get传递的数据(格式为查询字符串)
//获取请求的url,获取请求的方法,请求对象下面的,拿到url,就相当于拿到了查询字符串
console.log(req.url,req.method);
//express框架里面就有了提供了query方法,内部把乱码解析为对象
console.log(req.query);
res.send('搜索成功');
})
//第一个路由:手动输入/search,获取/search.html页面
//第二个路由:点击按钮搜索发出请求/mysearch,目的是为了获取浏览器向服务器传递的关键字叫'查询字符串'
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LLa8m2wU-1635344489971)(C:\Users\23204\AppData\Roaming\Typora\typora-user-images\image-20211001170034470.png)]
三、路由中获取数据
1、get方法
格式为:http://127.0.0.1:8080/mysearch?keyword=笔记本
路由中获取,结果为对象:req.query()
,结果为{keyword=笔记本}
案例:添加路由(get /login),响应登录的网页login.html,点击提交向服务器发请求(get /mylogin),添加对应的路由,获取传递的数据,响应“登录成功,欢迎:xxx”
<!DOCTYPE html>
<html lang="en">