XML简介
1、XML:可扩展标记语言;
2、XMl被设计用来传输和存储数据;
3、XML和HTML类似,不同的是HTML中都是预定义标签,而XML中没有预定义标签,全部都是自定义标签,用来表示一些数据。
// 一个学生的数据
name="孙悟空";age=18;gender="男";
// XML表示
<student>
<name>孙悟空</name>
<age>18</age>
<gender>男</gender>
</student>
现在已经被json取代
// 用JSON表示:
{name:'孙悟空',age:18,gender:'男'}
AJAX的优缺点
1、优点:
1)可以无需刷新页面而与服务器端进行通信;
2)允许根据用户事件来更新部分页面内容;
2、缺点:
1)没有浏览历史,不能回退
2)存在跨域问题(同源)
3)SEO不友好
HTTP协议请求报文与响应文本结构
HTTP(hypertext transport protocol)协议「超文本传输协议」,协议详细规定了浏览器和万维网服务器之间互相通信的规则。
1、请求报文
行 GET /s?ie=utf-8 HTTP/1.1
头 Host: atguigu.com
Cookie: name=guigu
Content-type: application/x-www-form-urlencoded
User-Agent: chrome 83
空行
体 (get请求的请求体为空)
2、响应报文
行 HTTP/1.1 200 OK
头 Content-Type: text/html;charset=utf-8
Content-length: 2048
Content-Encoding: gzip
空行
体
express框架介绍与基本使用
1、安装
yarn add express
2、使用
// express.js
// import express from 'express'
const express = require('express')
const app = express()
app.get('/',(request,response)=>{
// 设置请求头 允许跨域
response.setHeader('Access-Control-Allow-Origin', '*')
// 设置响应体
response.send('HELLO EXPRESS')
// console.log('HELLO EXPRESS')
})
app.listen(8000,()=>{
console.log('服务启动成功...')
})
node express.js
nodemon:自动重启express工具
# 安装
sudo yarn add nodemon global
# 启动
nodemon express.js
AJAX请求的基本操作
// get请求
// 1、创建对象
const xhr = new XMLHttpRequest()
// 2、初始化 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/server')
// 3、发送
xhr.send()
// 4、事件绑定,处理服务端返回的结果
/*
on => when 当...时候
readystate 是xhr对象中的属性,表示状态
0:创建对象成功
1:已调用open方法
2:send方法已调用
3:服务端返回了部分的结果
4:服务端返回了所有的结果
change 改变 改变4次
*/
xhr.onreadystatechange = function(){
// 判断(服务端返回了所有的结果)
if(xhr.readyState === 4){
// 判断响应状态码 2xx(基本上是成功的) 4xx 5xx
if(xhr.status >= 200 && xhr.status <300){
// 处理结果 行、头、空行、体
1、响应行
console.log(xhr.status) // 状态码
console.log(xhr.statusText) // 状态字符串
console.log(xhr.getAllResponseHeaders()) // 所有响应头
console.log(xhr.response) // 响应体
}else{
}
}
}
AJAX设置请求参数
// GET请求
const xhr = new XMLHttpRequest()
xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300')
xhr.send()
xhr.onreadystatechange = function(){
// 注意大小写
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status <300){
console.log('请求成功')
console.log('xhr===>',xhr)
}
}
}
// POST请求
const xhr = new XMLHttpRequest()
xhr.oepn('post','http://127.0.0.1:8000/server')
xhr.send('a=100&b=200&c=100')
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
console.log('xhr===>', xhr)
}
}
}
AJAX设置请求头信息
const xhr = new XMLHttpRequest()
xhr.open('post','http://127.0.0.1:8000/post-server')
xhr.send('a=100&b=200')
// 设置请求头
/*
格式 xhr.setRequestHeader('','')
可以自定义,但express需要加上设置:
1、response.setHeader('Access-Control-Allow-Header', '*')
2、后端app.post需要改成app.all
Content-Type:设置请求体类型
*/
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status <= 200 && xhr.status < 300){
}
}
}
服务端响应JSON数据
// 在express服务端 response.send({}),客户端xhr.response得到的是字符串
// 拿到json数据有两种方式
/*
获取json数据有两种方式
1、获取到xhr.response之后进行数据转换
2、在xhr.open()之前设置xhr.responseType = 'json'
*/
IE缓存问题的解决
const xhr = new XMLHttpRequest()
// 关键在于给每次请求加上一个时间戳
xhr.open('get',`http://127.0.0.1:8000?ie?t=${Date.now()}`)
xhr.send()
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
}
}
}
请求超时与网络异常处理
const xhr = XMLHttpRequest()
xhr.open('get','http://127.0.0.1:8000/delay')
// 设置超时
xhr.timeout = 2000
// 捕获超时
xhr.ontimeout = () => {
alert('网络超时')
}
// 捕获网络异常
xhr.onerror = () => {
alert('网络异常')
}
xhr.send()
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
}
}
}
取消请求(abort)与重复请求问题
// 假设html上有两个按钮,第一个是发送请求,第二个是取消请求
let xhr = null
// 发送请求
document.getElementById('sendBtn').onclick = {
xhr.open('get', 'http://127.0.0.1:8000/delay')
xhr.send()
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
}
}
}
}
// 取消请求
document.getElementById('obortBtn').onclick = {
xhr && xhr.abort()
}
jQuery发送AJAX请求( . g e t ( ) , .get(), .get(),.post())
<!-- 首先需要引入jQuery -->
<!--
crossorigin:一个跨域源请求的属性设置
anonymous:匿名,像src中的资源发送请求时不会携带cookie
-->
<script crossorigin="anonymous" src="..." />
$('#getBtn').click(()=>{
// 请求方式、请求地址、请求参数、回调函数、响应体类型
$.get('http://127.0.0.1:8000/jquery', {a: 100, b: 200}, function(data){
})
$.post('http://127.0.0.1:8000/jquery', {a: 100, b: 200}, function(data){
})
})
jQuery通过方法发送AJAX请求($.ajax())
$.ajax({
url: 'http://127.0.0.1:8000/jquery',
data: {a: 100, b: 200},
type: 'GET',
dataType: 'json',
timeout: 2000,
/*
需要在后台设置允许自定义请求头
response.setHeader('Access-Control-Allow-Headers', '*')
*/
headers:{
c: 300,
d: 400
},
success: function(data){
console.log(data)
},
error: function(data){
console.error(data)
}
})
axios发送AJXAX请求
axios.default.baseURL = 'http://127.0.0.1:8000'
// get请求
axios.get('/axios-server',{
params: {
id: 1,
vip: 7
},
headers: {
name: 'Tom',
age: 20,
},
}).then(res => {
console.log(res)
})
// post请求
axios.post('/axios-server', {
userName: 'Tom',
password: 123
}, {
// url
params: {
id: 200,
vip: 9
},
headers: {
height: 180,
weight: 180
}
})
// 通用方法
axios({
method: 'post',
url: '/axios-server',
params: {
vip: 19,
level: 30
},
// 头信息
headers: {
a: 100,
b: 200
},
data: {
userName: 'admin',
password: 'admin',
}
}).then(response => {
console.log(response)
})
使用fetch函数发送AJAX请求
fetch('http://127.0.0.1:8000/fetch-server?vip=10', {
method: 'POST',
headers: {
name: 'TOM',
},
// 请求体
body: 'username=admin&password=admin'
}).then(response => {
// 返回字符串
// return response.text()
// 返回json
retrun response.json()
}).then(response => {
console.log(response)
})
同源策略(Same-Origin Policy)
最早由Netscape公司 提出,是浏览器的一种安全策略。
同源协议:协议、域名、端口号 必须完全相同。
违背同源策略就是跨域。
如何解决跨域
- JSONP
- JSONP是什么?
JSONP(JSON.with Padding),是一个非官方的跨域解决方案,只支持get请求。
- JSONP怎么工作的?
在网页有一些标签天生具有跨域能力,比如:img,link,iframe,script。
JSONP就是利用script标签的跨域能力来发送请求的。
...
<body>
<script src="http://127.0.0.1:8000/.../server" ></script>
</body>
...
// 服务端
app.all('/server', (request, response)=>{
// 这里返回的代码会被浏览器执行
// response.send('console.log("hellp jsonp")')
// 正是因为返回的代码会被浏览器执行,所以jsonp就是利用了这个原理
const data = {
name: 'TOM'
}
// 将数据转化为字符串
const str = JSON.stringify(data)
/*
返回结果
1、这里把 send() 改成了 end() 是因为end返回结果不会加特殊响应头
2、返回 函数调用的函数名在客户端中必需存在才有意义
*/
response.end(`handle(${str})`)
})
- JSONP的使用
<body>
<div>
用户名:<input type="text" id="username" />
<p></p>
</div>
<script>
const input = document.getElementById('username')
const p = document.querySelector('p')
function handle(data){
input.style.border = 'solid 1px #ccc'
p.innerHTML = data.msg
}
input.onblur = function(){
const username = this.value
// 1、创建script标签
const script = document.createElement('script')
// 2、设置标签的src属性
script.src = 'http://127.0.0.1:8000/server'
// 3、将script插入到文档中
document.body.appendChild(script)
}
</script>
</body>
- jQuery发送JSONP请求
// ?callback=? 固定的格式
$.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?', function(data){
console.log(data)
})
// 服务端
// 接收 callback 参数
let cb = request.query.callback
// 返回结果
response.end(`${cb}(${str})`)
- CORS
- CORS(Cross-Origin Resource Sharing)是什么?
跨域资源共享。CORS是官方的跨域解决方案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持get和post请求。跨域资源共享标准新增了一组HTTP首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源。
- CORS怎么工作的?
CORS是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应以后,就会对响应放行。
- CORS的使用
主要是服务器端的设置:
// 允许所有跨域
response.setHeader('Access-Control-Allow-Origin', '*')
// 允许的请求头
response.setHeader('Access-Control-Allow-Origin', '*')
// 允许的请求方法
response.setHeader('Access-Control-Allow-Method', '*')