机构编制网站建设,页面风格分哪些风格,凉山建设网站,Godaddy如何建设网站HTTP知识
HTTP#xff08;hypertext transport protocol#xff09;协议『超文本传输协议』#xff0c;协议详细规定了浏览器和万维网服务器之间互相通信的规则。
请求报文
请求行: GET、POST /s?ieutf-8...#xff08;url的一长串参数#xff09; HTTP/1.1
请求头…HTTP知识
HTTPhypertext transport protocol协议『超文本传输协议』协议详细规定了浏览器和万维网服务器之间互相通信的规则。
请求报文
请求行: GET、POST /s?ieutf-8...url的一长串参数 HTTP/1.1
请求头: Host: atguigu.comCookie: nameguiguContent-type: application/x-www-form-urlencodedUser-Agent: chrome 83...空行
请求体: usernameadminpasswordadmin Post、Put有点击原始才可看到请求行等详情信息。 Get请求载荷url的发送的json格式参数。 Post请求体发送的表单数据 响应报文
响应行 HTTP/1.1 200 OK
响应头 Content-Type: text/html;charsetutf-8Content-length: 2048Content-encoding: gzip...空行
响应体 htmlhead/headbodyh1尚硅谷/h1/body/html响应体这里返回的是HTML文本显示网页。 原生AJAX
AJAX简介
AJAX 全称为 Asynchronous JavaScript And XML 就是异步的 JS 和 XML。
XML简介
XML 可扩展标记语言。 XML 被设计用来传输和存储数据。
XML 和 HTML 类似 不同的是 HTML 中都是预定义标签 而 XML 中没有预定义标签全都是自定义标签 用来表示一些数据
studentname孙悟空/nameage18/agegender男/gender
/student现在已经被 JSON 取代了。
{name:孙悟空,age:18,gender:男
}AJAX的使用
核心对象
XMLHttpRequest AJAX 的所有操作都是通过该对象进行的。
使用步骤
// 1) 创建 XMLHttpRequest 对象
var xhr new XMLHttpRequest();// 2) 设置请求信息
xhr.open(method, url);// 可以设置请求头 一般不设置
xhr.setRequestHeader(Content-Type, application/x-www-form-urlencoded);//3) 发送请求
xhr.send(body) //get 请求不传 body 参数 只有 post 请求使用4) 接收响应
//xhr.responseXML 接收 xml 格式的响应数据
//xhr.responseText 接收文本格式的响应数据
xhr.onreadystatechange function (){if(xhr.readyState 4 xhr.status 200){var text xhr.responseText;console.log(text);}
}get请求
客户端
bodybutton点击发送请求/buttondiv idresult/divscript//获取button元素const btn document.getElementsByTagName(button)[0];const result document.getElementById(result);//绑定事件btn.onclick function(){//1. 创建对象const xhr new XMLHttpRequest();//2. 初始化 设置请求方法和 urlxhr.open(GET, http://127.0.0.1:8000/server?a100b200c300);//3. 发送xhr.send();//4. 事件绑定 处理服务端返回的结果// readystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4//0:未初始化 1open方法调用完毕 2.send调用完毕 3.服务端返回了部分结果 4.服务端返回了所有结果// change 改变xhr.onreadystatechange function(){ //状态每次改变就会触发函数//判断 (服务端返回了所有的结果)if(xhr.readyState 4){//判断响应状态码 200 404 403 401 500// 2xx 成功if(xhr.status 200 xhr.status 300){//处理结果 行 头 空行 体//响应 // console.log(xhr.status);//状态码 200// console.log(xhr.statusText);//状态字符串 OK// console.log(xhr.getAllResponseHeaders());//所有响应头// console.log(xhr.response);//响应体//设置 result 的文本result.innerHTML xhr.response;}else{}}}}/script
/body服务端:
//1. 引入express
const express require(express);//2. 创建应用对象
const app express();//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.get(/server, (request, response) {//设置响应头 设置允许跨域response.setHeader(Access-Control-Allow-Origin, *);//设置响应体response.send(HELLO AJAX - 2);
});//4. 监听端口启动服务
app.listen(8000, () {console.log(服务已经启动, 8000 端口监听中....);
});post请求
xhr.open(POST, http://127.0.0.1:8000/server);
xhr.setRequestHeader(Content-Type,application/x-www-form-urlencoded);
xhr.setRequestHeader(name,atguigu); // 会报错因为不是预定义标签要进行相关设置
// 请求体
xhr.send(a100b200c300);
// xhr.send(a:100b:200c:300);// 服务端
// 接受post请求
app.post(/server, (request, response) {response.setHeader(Access-Control-Allow-Origin, *);response.setHeader(Access-Control-Allow-Headers, *);response.send(HELLO AJAX POST);
});//服务端
//可以接收任意类型的请求
app.all(/server, (request, response) {
});返回Json类型
// 客户端
const xhr new XMLHttpRequest();//设置响应体数据的类型
xhr.responseType json;xhr.open(GET,http://127.0.0.1:8000/json-server);
xhr.send();
xhr.onreadystatechange function(){if(xhr.readyState 4){if(xhr.status 200 xhr.status 300){//// console.log(xhr.response);// result.innerHTML xhr.response;// 1. 手动对数据转化// let data JSON.parse(xhr.response); //将响应文本转换为JSON类型// console.log(data);// result.innerHTML data.name;// 2. 自动转换console.log(xhr.response);result.innerHTML xhr.response.name;}}
}// 服务端
//JSON 响应
app.all(/json-server, (request, response) {response.setHeader(Access-Control-Allow-Origin, *);response.setHeader(Access-Control-Allow-Headers, *);const data {name: atguigu};//将data变量转换为 JSON 字符串let str JSON.stringify(data);response.send(str);
});超时与网络异常
// 客户端
btn.addEventListener(click, function(){const xhr new XMLHttpRequest();//超时设置 2s 设置xhr.timeout 2000;//超时回调xhr.ontimeout function(){alert(网络异常, 请稍后重试!!);}//网络异常回调xhr.onerror function(){alert(你的网络似乎出了一些问题!);}xhr.open(GET,http://127.0.0.1:8000/delay);xhr.send();xhr.onreadystatechange function(){if(xhr.readyState 4){if(xhr.status 200 xhr.status 300){result.innerHTML xhr.response;}}}
})// 服务端
//延时响应
app.all(/delay, (request, response) {response.setHeader(Access-Control-Allow-Origin, *);response.setHeader(Access-Control-Allow-Headers, *);setTimeout(() {response.send(延时响应);}, 3000)
});取消请求
// 客户端
button点击发送/button
button点击取消/button
script//获取元素对象const btns document.querySelectorAll(button);let x null;btns[0].onclick function(){x new XMLHttpRequest();x.open(GET,http://127.0.0.1:8000/delay);x.send();}// abort 取消正在pending的请求btns[1].onclick function(){x.abort();}
/script解决重复请求问题
button点击发送/button
script//获取元素对象const btns document.querySelectorAll(button);let x null;//标识变量let isSending false; // 是否正在发送AJAX请求btns[0].onclick function(){//判断标识变量if(isSending) x.abort();// 如果正在发送, 则取消该请求, 创建一个新的请求x new XMLHttpRequest();//修改 标识变量的值isSending true;x.open(GET,http://127.0.0.1:8000/delay);x.send();x.onreadystatechange function(){// 这里不判断状态码是因为可能请求是失败的则会导致走不到x.readyState 4这个判断无法修改isSendingif(x.readyState 4){//修改标识变量isSending false;}}}
/scriptJQuery发送AJAX
get请求
$.get(url, [data], [callback], [type])
url:请求的 URL 地址。
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式 xml, html, script, json, text, _default。// 客户端
$(button).eq(0).click(function(){// {a:100, b:200} get携带的参数 在url后面$.get(http://127.0.0.1:8000/jquery-server, {a:100, b:200}, function(data){console.log(data);},json);
});// 服务端
//jQuery 服务
app.all(/jquery-server, (request, response) {response.setHeader(Access-Control-Allow-Origin, *);response.setHeader(Access-Control-Allow-Headers, *);// response.send(Hello jQuery AJAX);const data {name:尚硅谷};response.send(JSON.stringify(data));
});post请求
$.post(url, [data], [callback], [type])
url:请求的 URL 地址。
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式 xml, html, script, json, text, _default。$(button).eq(1).click(function(){// {a:100, b:200} form data 请求体$.post(http://127.0.0.1:8000/jquery-server, {a:100, b:200}, function(data){console.log(data);});
});JQuery通用方法发送请求
$(button).eq(2).click(function(){$.ajax({//urlurl: http://127.0.0.1:8000/jquery-server,//参数data: {a:100, b:200},//请求类型type: GET,//响应体结果dataType: json,//成功的回调success: function(data){console.log(data);},//超时时间timeout: 2000,//失败的回调error: function(){console.log(出错啦!!);},//头信息headers: {c:300,d:400}});
});aioxs发送请求
https://github.com/axios/axios
特点
Make XMLHttpRequests from the browserMake http requests from node.jsSupports the Promise API 支持 ES6 Promise APIIntercept request and responseTransform request and response dataCancel requestsAutomatic transforms for JSON data 自动转换JSON数据 Automatic data object serialization to multipart/form-data and x-www-form-urlencoded body encodingsClient side support for protecting against XSRF
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.delete(url[, config])Get请求
// https://github.com/axios/axios
const btns document.querySelectorAll(button);//配置 baseURL
axios.defaults.baseURL http://127.0.0.1:8000;btns[0].onclick function () {//GET 请求axios.get(/axios-server, {//url 参数params: {id: 100,vip: 7},//请求头信息headers: {name: atguigu,age: 20}}).then(data {// handle successconsole.log(data);}).catch(error {// handle error}).finally(() {// always executed});
}响应结果展示 Post请求
btns[1].onclick function () {//Post请求axios.post(/axios-server, { //请求体 username: admin,password: admin}, {//url 参数params: {id: 200,vip: 9},//请求头参数headers: {height: 180,weight: 180,}}).catch(error {// handle error}).finally(() {// always executed});
}通用方法发送请求
btns[2].onclick function(){axios({//请求方法method : POST,//urlurl: /axios-server,//url参数params: {vip:10,level:30},//头信息headers: {a:100,b:200},//请求体参数data: {username: admin,password: 123456}}).then(response {//响应状态码console.log(response.status);//响应状态字符串console.log(response.statusText);//响应头信息console.log(response.headers);//响应体console.log(response.data);}).catch(error {// handle error}).finally(() {// always executed});
}跨域
同源策略
同源策略(Same-Origin Policy)最早由 Netscape 公司提出 是浏览器的一种安全策略
同源 协议、 域名、 端口号 必须完全相同。
违背同源策略就是跨域。
同源情况
// 服务端
const express require(express);const app express();app.get(/home, (request, response){//响应一个页面response.sendFile(__dirname /index.html);
});app.get(/data, (request, response){response.send(用户数据);
});app.listen(9000, (){console.log(服务已经启动...);
});// 客户端!-- index.html --
h1尚硅谷/h1
button点击获取用户数据/button
scriptconst btn document.querySelector(button);btn.onclick function(){const x new XMLHttpRequest();//这里因为是满足同源策略的, 所以 url 可以简写x.open(GET,/data);x.send();x.onreadystatechange function(){if(x.readyState 4){if(x.status 200 x.status 300){console.log(x.response);}}}}
/script在localhost9000 端口下的index页面点击button发送请求这个请求也是本地端口下的服务。因此是同源的。
解决跨域问题
CORS
简介
CORSCross-Origin Resource Sharing 跨域资源共享。 CORS 是官方的跨域解决方案 它的特点是不需要在客户端做任何特殊的操作 完全在服务器中进行处理 支持get 和 post 请求。 跨域资源共享标准新增了一组 HTTP 首部字段 允许服务器声明哪些源站通过浏览器有权限访问哪些资源。
工作
CORS 是通过设置一个响应头来告诉浏览器 该请求允许跨域 浏览器收到该响应以后就会对响应放行。
使用
后端设置响应头部信息 在服务端后端对应的接口中设置合适的响应头部信息允许指定域名或允许所有域名访问如设置 Access-Control-Allow-Origin 为 ‘*’表示允许所有域名)。
//设置响应头 设置允许跨域
response.setHeader(Access-Control-Allow-Origin, *);// 其他设置
// 允许所有Headers
response.setHeader(Access-Control-Allow-Headers, *);
// 允许所有方法请求get/post/put/delete...
response.setHeader(Access-Control-Allow-Method, *);其他解决跨域问题
使用代理 在开发环境下可以通过配置代理来规避跨域问题。即在前端发送请求时先将请求发送到自己的服务器域名前端一致再由自己的服务器转发请求到目标后端服务然后将后端服务的响应返回给前端。这种方式需要自己搭建代理服务器。小程序开发工具配置不校验合法域名 在微信开发者工具中可以临时关闭域名校验但这仅适用于开发阶段上线时不建议关闭域名校验。