• AJAX请求以及解决跨域的问题


    学习ajax必须得掌握的就是跨域请求,实际上在不同源的地址上发送请求就是跨域请求,本文主要给大家介绍了关于AJAX请求以及解决跨域问题的相关资料,需要的朋友可以参考下

    AJAX 介绍

    AJAX其实就是异步的js和xml

    通过ajax可以在浏览器中发送异步请求。

    最大优势:无刷新获取数据

    优点

    1.可以无需刷新页面与服务器进行通信

    2.允许根据用户事件更新部分页面内容

    当然也存在其缺点问题:比如跨域问题等!

    一.原生AJAX请求(GET)

    由于get和post请求类似,原生代码相比jQuery复杂一些:原生代码演示get请求 jquery演示get和post请求

    代码中会出现node.js的相关代码,比如express框架,对node.js不熟悉的同学可以先注重前端代码
    前端代码:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title> GET 请求</title>
    8. <style>
    9. #result{
    10. width: 100px;
    11. height: 100px;
    12. border: 1px solid pink;
    13. }
    14. </style>
    15. </head>
    16. <body>
    17. <button class="btn">发送请求</button>
    18. <div id="result"></div>
    19. <script>
    20. var btn=document.querySelector(".btn")
    21. const result=document.getElementById("result")
    22. btn.addEventListener("click",function(){
    23. //1.创建对象
    24. const xhr=new XMLHttpRequest()
    25. //2.初始化 设置请求方法和url
    26. xhr.open("GET","http://127.0.0.1:3000/server?a=100&b=200");//?后面是get请求加参数方法
    27. //3.发送
    28. xhr.send()
    29. //4.事件绑定 处理服务端返回的结果
    30. xhr.onreadystatechange=function(){
    31. if(xhr.readyState===4){
    32. //判断响应状态码
    33. if(xhr.status>=200 && xhr.status<=300){
    34. console.log(xhr.status);//状态码
    35. console.log(xhr.statusText);//状态字符串
    36. console.log(xhr.getAllResponseHeaders());//所有响应头
    37. console.log(xhr.response);//响应体
    38. result.innerHTML=xhr.response//把响应结果给div盒子
    39. }
    40. }
    41. }
    42. })
    43. </script>
    44. </body>
    45. </html>

    服务端代码

    1. const express=require("express")
    2. const app = express();
    3. //1.对应get请求
    4. app.get("/server",(req,res)=>{
    5. //设置响应头
    6. res.setHeader("Access-Control-Allow-Origin","*")
    7. //这里设置响应头允许所有域都具有访问资源的权限。
    8. //不设置就存在跨域问题,访问不到,后面我们会介绍另外一种比较简单的解决方法
    9. //设置响应体
    10. res.send("hello GET-AJAX")
    11. })
    12. app.listen(3000,()=>{
    13. console.log("服务启动");
    14. })

    二.jQuery AJAX请求(GET 和POST)

    先了解一下jQuery中AJAXGET请求和POST请求语法:

    get 请求
    $.get(url, [data], [callback], [type])
    url:请求的 URL 地址。
    data:请求携带的参数。
    callback:载入成功时回调函数。
    type:设置返回内容格式,xml, html, script, json, text,_default。
    post 请求
    $.post(url, [data], [callback], [type])
    url:请求的 URL 地址。
    data:请求携带的参数。
    callback:载入成功时回调函数。
    type:设置返回内容格式,xml, html, script, json, text,
    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    6. <title>jQuery 发送 AJAX 请求</title>
    7. <script
    8. crossorigin="anonymous"
    9. src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"
    10. ></script>
    11. </head>
    12. <body>
    13. <button >GET</button>
    14. <button >POST</button>
    15. <script>
    16. //jQuery发送AJAX请求 -get请求
    17. $("button").eq(0).click(function () {
    18. $.get("http://127.0.0.1:5000/jquery-server", { a: 1, b: 2 }, (data) => {
    19. console.log(data);
    20. },"json"
    21. );
    22. });
    23. //jQuery发送AJAX请求 -post请求
    24. $("button").eq(1).click(function () {
    25. $.post( "http://127.0.0.1:5000/jquery-server", { a: 1, b: 2 },(data) => {
    26. console.log(data);
    27. }, "json"
    28. );
    29. });
    30. </script>
    31. </body>
    32. </html>

     

    服务端代码:

    这里使用app.all()使得所有请求方法都可以访问

    1. const express = require('express');
    2. const app = express();
    3. //jQuery 服务 这里使用app.all()使得所有请求方法都可以访问
    4. app.all('/jquery-server', (request, response) => {
    5. //设置响应头 设置允许跨域
    6. response.setHeader('Access-Control-Allow-Origin', '*');
    7. response.setHeader('Access-Control-Allow-Headers', '*');
    8. // response.send('Hello jQuery AJAX get');
    9. const data = {name:'小吴同学'};
    10. response.send(JSON.stringify(data));
    11. });
    12. //4. 监听端口启动服务
    13. app.listen(5000, () => {
    14. console.log("服务启动");
    15. });

     

    三.跨域问题的解决

    跨域问题:当我们的浏览器从一个域名的网页去请求另一个域名的资源时,其中域名、端口、协议任一不同,都是属于跨域

    示范例子

    前端请求代码如下 :

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>CORS</title>
    7. <style>
    8. #result{
    9. width:200px;
    10. height:100px;
    11. border:solid 1px pink;
    12. }
    13. </style>
    14. </head>
    15. <body>
    16. <button class="btn">发送请求</button>
    17. <div id="result"></div>
    18. <script>
    19. const btn = document.querySelector('.btn');
    20. btn.onclick = function(){
    21. const xhr = new XMLHttpRequest();
    22. xhr.open("GET", "http://127.0.0.1:5000/server");
    23. xhr.send();
    24. xhr.onreadystatechange = function(){
    25. if(xhr.readyState === 4){
    26. if(xhr.status >= 200 && xhr.status < 300){
    27. //输出响应体
    28. console.log(xhr.response);
    29. result.innerHTML=xhr.response
    30. }
    31. }
    32. }
    33. }
    34. </script>
    35. </body>
    36. </html>

    服务端我介绍两种简单且效率极高的方法解决跨域问题

    1.在服务端设置header

    1. const express = require('express');
    2. const app = express();
    3. app.all('/server', (request, response)=>{
    4. //设置响应头方法
    5. response.setHeader("Access-Control-Allow-Origin", "*");
    6. response.setHeader("Access-Control-Allow-Headers", '*');
    7. response.setHeader("Access-Control-Allow-Method", '*');
    8. response.send('设置响应头解决跨域问题成功');
    9. });
    10. app.listen(5000, () => {
    11. console.log("服务启动");
    12. });

    2.使用中间件cors

    1. const express = require('express');
    2. const app = express();
    3. //使用cors中间件方法
    4. const cors=require("cors")
    5. app.use(cors())
    6. app.all('/server', (request, response)=>{
    7. response.send('使用cors中间件解决跨域问题成功');
    8. });
    9. app.listen(5000, () => {
    10. console.log("服务启动");
    11. });

    这里给大家具体讲一下cors中间件使用步骤

    1.在终端使用 npm i cors 命令下载这个中间件

    2.使用require导入cors中间件:const cors=require(“cors”)

    3.用app.use()方法注册中间件:app.use(cors()) 注意:这个注册方法一定要写在在配置路由之前

    四.其他解决跨域问题方法

    一.JSONP跨域

    JSONP(JSON with Padding),是一个非官方的跨域解决方案,只支持get请求(具有局限性)

    工作原理:JSONP 就是利用 script 标签的跨域能力来发送请求的。

    二.nginx反向代理

    大致解释:

    www.A.com/index.html需要调用www.B.com/server.js,可以写一个中间接口www.A.com/server.js,靠着这个接口在服务端

    去调用www.B.com/server.js并拿到返回值,然后再返回给index.html

    这个方法一般很少使用,它可以不用目标服务器与前端配合,但是需要搭建一个中转nginx服务器,用于转发请求。

  • 相关阅读:
    红队攻防渗透技术实战流程:中间件安全:IIS&NGINX&APACHE&TOMCAT
    深入解析Spring Boot中最常用注解的使用方式(上篇)
    u-blox模块-- UBX protocol(NEO-M9N-00B-00)
    AI 编程探索- iOS动态标签控件
    React源码分析3-render阶段(穿插scheduler和reconciler)
    Servlet API详解
    fastapi_No.21_安全性_目录权限认证
    相控阵天线(九):平面阵列天线综合(不可分离型切比雪夫分布、圆口径泰勒综合、可分离型分布、配相抵消法)
    7.网络原理之TCP_IP(上)
    【UCB操作系统CS162项目】Lab0:项目上手 (Getting Real)
  • 原文地址:https://blog.csdn.net/lwf3115841/article/details/128062794