HTTP HTTP(HyperText Transport Protocol)
协议,也就是超文本传输协议,详细规定了浏览器和万维网服务器之间相互通信的规则
请求报文 格式与参数
1 2 3 4 5 6 7 行 POST /s?ie=utf-8 HTTP/1.1 头 HOST: herrick.3 vhost.net Cookie: name=herrick Content-type: application/x-www-form-urlencoded User-Agent: chorome-83 空行 体
响应报文 1 2 3 4 5 6 7 8 9 10 11 12 行 HTTP/1.1 200 OK 头 Content-Type: text/html;charset=utf-8 Content-length: 2048 Content-encoding: gzip 空行 体 <html> <head> </head> <body> <h1>标题</h1> </body> </html>
express 框架 express
框架是一个简介而灵活的node.js
Web
应用框架,提供了一系列强大的特性创建各种 Web 应用和丰富的HTTP
工具。
使用express
框架可以快速搭建一个完整功能的网站,所以我们可以利用express
模拟一个后端服务的环境
首先在项目包里利用npm
下载express
npm i express
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 - 创建一个`server.js`文件 - ```javascript //引入express const { response } = require("express"); const express = require("express"); //创建应用对象 const app = express(); //创建路由规则 //request对请求报文封装 //respose对相应报文封装 app.get("/", (request, response) => { //设置响应 response.send("hello express"); }); app.listen(8000, () => { console.log("服务已经启动,8000端口监听中...."); });
然后node server.js
,注意路径需要cd
到当前包下
此时服务已经启动,控制台显示服务已经启动,8000端口监听中....
,网址输入localhost:8000
能够看到hello express
原生 Ajax 创建两个文件,一个HTML
和一个server.js
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 const express = require ("express" );const app = express ();app.get ("/server" , (request, response ) => { response.setHeader ("Access-Control-Allow-Origin" , "*" ); response.send ("hello express" ); }); app.listen (8000 , () => { console .log ("服务已经启动,8000端口监听中...." ); });
.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 <!DOCTYPE html > <html > <head > <meta charset ="utf-8" /> <meta http-equiv ="X-UA-Compatible" content ="IE=edge" /> <title > AJAX GEt 请求</title > <meta name ="description" content ="" /> <meta name ="viewport" content ="width=device-width, initial-scale=1" /> <link rel ="stylesheet" href ="" /> </head > <body > <button > 点击发送请求</button > <div id ="result" > </div > <script > const btn = document .getElementsByTagName ("button" )[0 ]; const result = document .getElementById ("result" ); btn.onclick = function ( ) { const xhr = new XMLHttpRequest (); xhr.open ("GET" , "http://localhost:8000/server" ); xhr.send (); xhr.onreadystatechange = function ( ) { if (xhr.readyState === 4 ) { if (xhr.status >= 200 && xhr.status < 300 ) { console .log (xhr.status ); console .log (xhr.statusText ); console .log (xhr.getAllResponseHeaders ()); console .log (xhr.response ); result.innerHTML = xhr.response ; } else { } } }; console .log ("test" ); }; </script > </body > <style > #result { width : 300px ; height : 200px ; border : solid 1px black; } </style > </html >
实现效果如下:
点击发送请求会在显示框内打印出响应体,同时在控制台显示请求信息
以上就完成了一个简单的GET
请求
接下来向服务端发起一个POST
请求
满足需求是:当鼠标移到显示框的时候,显示框能显示到服务端发来的响应体
修改HTML
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 <!DOCTYPE html > <html > <head > <meta charset ="utf-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <title > AJAX GEt 请求 </title > <meta name ="description" content ="" > <meta name ="viewport" content ="width=device-width, initial-scale=1" > <link rel ="stylesheet" href ="" > </head > <body > <button > 点击发送请求 </button > <div id ="result" > </div > <script > const result = document .getElementById ('result' ); result.addEventListener ("mousemove" , function ( ) { const xhr = new XMLHttpRequest (); xhr.open ("POST" , "http://localhost:8000/server" ) xhr.send (); xhr.onreadystatechange = function ( ) { if (xhr.readyState === 4 ) { if (xhr.status >= 200 && xhr.status < 300 ) { result.innerHTML = xhr.response ; } } } }) </script > </body > <style > #result { width : 300px ; height : 200px ; border : solid 1px black; } </style > </html >
但是此时如果将鼠标移动到框内,控制台会报错No 'Access-Control-Allow-Origin' header is present on the requested resource.
因为服务段没有与之匹配的响应规则。此时服务端的规则还是上一小节的GET
,所以需要向服务端server.js
添加以下规则:
1 2 3 4 5 6 app.get ("/server" , (request, response ) => { response.setHeader ("Access-Control-Allow-Origin" , "*" ); response.send ("hello express" ); });
重新启动服务node server.js
,再次在html
页面滑动鼠标到框内,显示响应体成功
POST 请求设置参数 POST
请求设置参数,请求体是在send()
里设置的,参数的形式任意,但是需要服务端能够处理
比如xhr.send('a=100&b=200&c=300')
,或者可以xhr.send('a:100&b:200&c:300')
,或者直接xhr.send('12341414141')
,只要服务端能够处理就可
Ajax 设置请求头信息 设置请求信息,只需要在open
()后面调用一个方法setRequestHeader
例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <script > const result = document .getElementById ("result" ); result.addEventListener ("mousemove" , function ( ) { const xhr = new XMLHttpRequest (); xhr.open ("POST" , "http://localhost:8000/server" ); xhr.setRequestHeader ("Content-Type" , "application/x-www-form-urlencoded" ); xhr.setRequestHeader ("name" , "herrick.3vhost" ); xhr.send (); xhr.onreadystatechange = function ( ) { if (xhr.readyState === 4 ) { if (xhr.status >= 200 && xhr.status < 300 ) { result.innerHTML = xhr.response ; } } }; }); </script >
服务端响应json
数据 实际工作中服务端返回数据多数情况都是以json
格式发送,那么返回的结果应该怎么处理很重要
首先向server.js
添加下面代码all
代表接收所有类型的请求
1 2 3 4 5 6 7 8 9 10 11 app.all ("/json-server" , (request, response ) => { response.setHeader ("Access-Control-Allow-Origin" , "*" ); const data = { name : "herrick" , }; let str = JSON .stringify (data); response.send (str); });
html
文件<script>
标签内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <script > const result = document .getElementById ("result" ); window .onkeydown = function ( ) { const xhr = new XMLHttpRequest (); xhr.open ("GET" , "http://localhost:8000/json-server" ); xhr.send (); xhr.onreadystatechange = function ( ) { if (xhr.readyState === 4 ) { if (xhr.status >= 200 && xhr.status < 300 ) { result.innerHTML = xhr.response ; } } }; }; </script >
当键盘按下之后,就能接收到服务端传来的json
数据
此时数据为一个json
格式字符串,我们需要将其变成一个对象
可以手动转换
1 2 let data = JSON.parse(xhr.response); //然后就可以使用data里面的数据 result.innerHTML = data.name;
更推荐自动转换
1 2 xhr.responseType = 'json' //然后就可以直接使用数据 result.innerHTML = xhr.response.name
nodemon
工具作用:自动检测文件改变重启服务
前提:node.js
1 2 3 4 5 6 7 8 9 10 11 npm i -g nodemon //再使用nodemon重启服务 nodemon server.js //部分用户会出现错误< nodemon : 无法加载文件XXX,因为在此系统上禁止运行脚本。>原因是powershell权限不够 //解决方法 1. win+R输入powershell 2. 输入start-proces s PowerShell -verb runas 进入管理员权限 3. 管理员身份输入set-Exe cutionPolicy RemoteSigned 选择y 4. 再次nodemon server.js 服务启动 nodemon启动服务后修改服务端代码后就无需重启服务
Ajax-IE 缓存问题解决 问题描述:IE 浏览器会对 Ajax 的请求结果做一个缓存,导致再次发送请求时走的时本地缓存而不是服务器返回的数据,导致最新数据不能接收。
解决方案:修改open()
1 2 xhr.open('GET', 'http://localhost:8000/json-server?t='+Date.now); // Date.now是一个时间戳,所以每次都会发送不同请求,浏览器就会判定为两次请求,也就解决了缓存问题
Ajax 请求超时和网络异常 例如:请求两秒为超时
1 2 3 4 5 6 7 8 9 10 //超时时间为2s xhr.timeout = 2000; //超时回调 xhr.ontimeout = function(){ alert("网络超时,请稍后重试!"); } //异常回调 xhr.onerror = function(){ alert("网络异常!"); }
Ajax 取消请求 调用XMLHttpRequest
的abort()
例如:
1 2 3 4 //按下按键取消请求 btn.onclick = function(){ xhr.abort(); }
Ajax 重复发送请求 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <script> let isSending = false ; btn.onclick = function ( ){ if (isSending)x.abort (); x = new XMLHttpRrequest (); isSending = true ; x.open ("GET" ,"http://localhost:8000" ); x.send (); x.onreadystatechange = function ( ){ if (x.readyState === 4 ){ isSending = false ; } } } </script>
Axios
发送Ajax
请求1 2 3 4 5 6 7 8 9 10 11 12 app.all ("/axios-server" , (request, response ) => { response.setHeader ("Access-Control-Allow-Origin" , "*" ); const data = { name : "herrick" , }; let str = JSON .stringify (data); response.send (str); });
1 2 3 4 <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.js" ></script>
1 2 3 4 5 6 7 8 9 10 11 <script> const btns = document .querySelectorAll ('button' ); btns[0 ].onclick = function ( ){" " } {axios.get ("http://localhost:8000/axios-server" , { params : { id : 10 , vip : 2 , }, })} </script>
此时控制台可以看到传递的参数