原生AJAX

  1. 创建对象

const xhr = new XMLHttpRequest();

  1. 初始化

xhr.open();

  1. 发送

xhr.send();

  1. 事件绑定

xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status <300){
result.innerHTML = xhr.response
}
}
}

  1. const btn = document.getElementsByTagName('button')[0];
  2. //绑定事件
  3. btn.onclick = function(){
  4. //1.创建对象
  5. const xhr = new XMLHttpRequest();
  6. //2.初始化 设置请求方法和url
  7. xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200');
  8. //3.发送
  9. xhr.send();
  10. //4.事件绑定 处理服务端返回的结果
  11. //readystate 是xhr对象中的属性,表示状态 0 1 2 3 4
  12. /*
  13. 0 未初始化
  14. 1 open方法已经调用完毕
  15. 2 send方法已经调用完毕
  16. 3 终端返回了部分接口
  17. 4 终端返回了所有接口
  18. */
  19. xhr.onreadystatechange = function(){
  20. //判断(服务端返回了所有的结果)
  21. if(xhr.readyState === 4){
  22. //判断响应状态码
  23. //2xx 成功
  24. if(xhr.status >= 200 && xhr.status < 300){
  25. //处理结果 行 头 空行 体
  26. // 响应
  27. // console.log(xhr.status)
  28. // console.log(xhr.statusText)//状态字符串
  29. // console.log(xhr.getAllResponseHeaders());//所有响应头
  30. // console.log(xhr.response);//响应体
  31. //设置result的文本
  32. result.innerHTML = xhr.response;
  33. }else{
  34. }
  35. }
  36. }
  37. }

取消请求 abort()

  1. <button>点击发送</button>
  2. <button>点击取消</button>
  3. <script>
  4. const btns = document.querySelectorAll('button');
  5. let x = null;
  6. btns[0].onclick = function(){
  7. x = new XMLHttpRequest;
  8. x.open('GET','http://127.0.0.1:8000/delay');
  9. x.send();
  10. }
  11. //abort
  12. btns[1].onclick = function(){
  13. x.abort();
  14. }
  15. </script>

JQuery发送AJAX请求

  1. $.ajax({
  2. //url
  3. url:'http://127.0.0.1:8000/jquery-server',
  4. //参数
  5. data:{a:100,b:200},
  6. //请求类型
  7. type:'GET',
  8. //响应体结果设置
  9. dataType:'json',
  10. //成功的回调
  11. success:function(data){
  12. console.log(data);
  13. },
  14. //超时事件
  15. timeout:2000,
  16. //失败的回调
  17. error:function(){
  18. console.log('出错啦');
  19. },
  20. //头信息
  21. headers:{
  22. c:300,
  23. d:400,
  24. }
  25. })
  1. //jQuery服务
  2. app.all('/jquery-server',(request,response)=>{
  3. //设置响应头 设置允许跨域
  4. response.setHeader('Access-Control-Allow-Origin','*');
  5. response.setHeader('Access-Control-Allow-Headers','*');
  6. // response.send('Hello jQuery AJAX')
  7. const data = {name:'尚硅谷'};
  8. response.send(JSON.stringify(data));
  9. });

Axios发送AJAX请求

  1. const btns = document.querySelectorAll('button');
  2. //配置baseURL
  3. axios.defaults.baseURL = 'http://127.0.0.1:8000';
  4. btns[0].onclick = function(){
  5. //GET 请求
  6. axios.get('/axios-server',{
  7. //url参数
  8. params:{
  9. id:100,
  10. vip:7
  11. },
  12. //请求头信息
  13. headers:{
  14. name:'atguigu',
  15. age:20
  16. }
  17. }).then(value => {
  18. console.log(value);
  19. });
  20. }
  21. btns[1].onclick = function(){
  22. axios.post('/axios-server',{
  23. username:'admin',
  24. password:'admin'
  25. },{
  26. //url
  27. params:{
  28. id:200,
  29. vip:9
  30. },
  31. //请求头参数
  32. headers:{
  33. height:108,
  34. weight:180,
  35. }
  36. })
  37. }
  38. btns[2].onclick = function(){
  39. axios({
  40. //url
  41. url:'/axios-server',
  42. //url参数
  43. params:{
  44. vip:10,
  45. level:30
  46. },
  47. //头信息
  48. headers:{
  49. a:100,
  50. b:200
  51. },
  52. //请求体参数
  53. data:{
  54. username:'admin',
  55. password:'admin'
  56. }
  57. }).then(response=>{
  58. console.log(response);
  59. //响应状态码
  60. console.log(response.status);
  61. //响应状态字符串
  62. console.log(response.statusText);
  63. //响应头信息
  64. console.log(response.headers);
  65. //响应体
  66. console.log(response.data);
  67. })
  68. }
  1. //axios服务
  2. app.all('/axios-server',(request,response)=>{
  3. //设置响应头 设置允许跨域
  4. response.setHeader('Access-Control-Allow-Origin','*');
  5. response.setHeader('Access-Control-Allow-Headers','*');
  6. // response.send('Hello jQuery AJAX')
  7. const data = {name:'尚硅谷'};
  8. response.send(JSON.stringify(data));
  9. });

fetch函数发送AJAX请求

  1. const btn = document.querySelector('button');
  2. btn.onclick = function(){
  3. fetch('http://127.0.0.1:8000/fetch-server',{
  4. //请求方法
  5. method:'POST',
  6. //请求头
  7. headers:{
  8. name:'atguigu'
  9. },
  10. //请求体
  11. body:'username=admin&password=admin'
  12. }).then(response=>{
  13. return response.json();
  14. }).then(response=>{
  15. console.log(response);
  16. })
  17. }
  1. //fetch服务
  2. app.all('/fetch-server',(request,response)=>{
  3. //设置响应头 设置允许跨域
  4. response.setHeader('Access-Control-Allow-Origin','*');
  5. response.setHeader('Access-Control-Allow-Headers','*');
  6. // response.send('Hello jQuery AJAX')
  7. const data = {name:'尚硅谷'};
  8. response.send(JSON.stringify(data));
  9. });

跨域

同源策略

协议(eg.http)、域名(eg:a.com)、端口号(eg.8000) 完全相同。
违背同源策略就是跨域。

解决跨域

JSONP(只支持get请求)

在网页有一些标签天生具有跨域能力,如img,link,iframe,script.
JSONP就是利用script标签的跨域能力来发送请求的。

CORS 跨域资源共享

后端用CORS添加请求头解决跨域。

配置代理(proxy)

代理,也称正向代理,是指一个位于客户端和目标服务器(target server)之间的服务器,为了从目标服务器取得内容,客户端向代理发送一个请求并指定目标(目标服务器),然后代理向目标服务器转交请求并将获得的内容返回给客户端。

nginx反向代理

webSocket协议跨域