zoukankan      html  css  js  c++  java
  • 跨域

    跨域

    1.什么是跨域

    1.1在不同的域访问

    当前从baidu.com----访问------>taobao.com,就是CORS跨域。

     

     当前从baidu.com----访问------>baidu.com,就是CORS跨域。

    验证:

    1.2在相同的域不同的端口也是跨域访问

     

    使用node.js来解释,先搭建node.js服务器。

     1.D盘下建立文件夹CORS

     2.VScode中打开,并在终端下安装npm install http-server和npm install express第三方模块。

     3.文件夹下建立server.js文件

    var express=require('express');
    
    //90端口的服务,将当前目录做为http服务
    var app=express();
    app.use(express.static(__dirname))
    app.listen(90)
    
    //91端口的服务,返回数据
    var app2=express();
    app2.get("/",function(req,res){
        res.send("你好")
    })
    app2.listen(91)

    4.文件夹下建立index.html文件

    <!DOCTYPE html>
    <html>
    
    <body>
        <h1>Hello!</h1>
    </body>
    
    </html>

    5.在终端启动server.js

    D:\CORS>node .\server.js

    6.浏览器查看结果

     7.现在修改index.html。让其访问同域的91端口

    <!DOCTYPE html>
    <html>
    
    <body>
        <h1>Hello!</h1>
        <script>
            fetch("http://localhost:91/")
            .then(res=>res.text())
            .then(data=>{alert(data)})
        </script>
    </body>
    
    </html>

    8.访问localhost:90端口,就是把server.js所在的文件夹作为根目录,默认访问的就是该文件夹下的index.html文件。但同时访问91端口,就会出现跨域失败。

    2.解决跨域的方法

    2.1第一种方法:修改响应头

     参考报错的提示,添加响应头

    var express=require('express');
    
    //90端口的服务,将当前目录做为http服务
    var app=express();
    app.use(express.static(__dirname))
    app.listen(90)
    
    //91端口的服务,返回数据
    var app2=express();
    app2.get("/",function(req,res){
        res.header("Access-Control-Allow-Origin","*")//响应头,任何域名
        res.send("你好")
    })
    app2.listen(91)

    运行localhost:90

     可以访问91端口,弹出对话框

    2.2第二种方法:jsonp

     我们知道通过href或src去请求的"js脚本"、“css文件”、“img图片文件”或者“视频文件”都不存在跨域问题,只有通过ajax请求下来的才存在跨域问题。jsonp就是通过这个来解决问题。

  • 相关阅读:
    浏览器原理
    jQ插件编写
    [转]清理浮动的全家
    百度面试~~
    LeetCode-222. Count Complete Tree Nodes
    LeetCode-236. Lowest Common Ancestor of a Binary Tree
    LeetCode-235. Lowest Common Ancestor of a Binary Search Tree
    LeetCode-102. Binary Tree Level Order Traversal
    LeetCode-404. Sum of Left Leaves
    LeetCode-257. Binary Tree Paths
  • 原文地址:https://www.cnblogs.com/szmtjs10/p/15613192.html
Copyright © 2011-2022 走看看