CORS如何解决

前端开发经常会遇到跨域问题。比如当前请求1baidu.com,如果想要从1请求2taobao.com的资源就会出现跨域的资源共享问题。不跨域就是我们就是请求1下的资源,不请求2的资源,就不是跨域问题:微信截图_20200319112724.png

在开发环境中经常会遇到这样的问题,接口在一台服务器或者一个端口上,而页面服务在另一个服务器或者端口,这样从前端获得接口的数据就会出现跨域的问题,那么如何解决跨域的问题?以下两种方案:

先写一个服务:

1
2
3
4
5
6
7
8
9
10
11
12
13
var express = required('expresss');

//90端口服务,将当前目录当成http服务,默认加载index.html
var app = express();
app.use(express.static(_dirname))
app.listen(90)

//91端口服务,返回数据
var app2 = express();
app2.get("/",function(req,res){
res.send("你好")
})
qpp2.listen(91)

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<body>
<h1>
hello!!
</h1>
<script>
fetch("http://localhost:91/")
.then(res=>res.txt())
.then(data=>{alert(data)})
</script>
</body>
</html>

这里接口不一致出现首图所示跨域问题

  • 修改相应头

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var express = required('expresss');

    //90端口服务,将当前目录当成http服务,默认加载index.html
    var app = express();
    app.use(express.static(_dirname))
    app.listen(90)

    //91端口服务,返回数据
    var app2 = express();
    app2.get("/",function(req,res){
    res.header("Access-Contorl-Allow-Origin","*")
    res.send("你好")
    })
    qpp2.listen(91)
  • jsonp

    服务:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    var express = required('expresss');

    //90端口服务,将当前目录当成http服务,默认加载index.html
    var app = express();
    app.use(express.static(_dirname))
    app.listen(90)

    //91端口服务,返回数据
    var app2 = express();
    app2.get("/",function(req,res){
    var funcname = req.query.callback;
    res.send(funcname+)
    res.send(funcname+"('你好')")
    //f("你好")
    })
    qpp2.listen(91)

    index.html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <!DOCTYPE html>
    <html>
    <body>
    <h1>
    hello!!
    </h1>
    <script>
    function f(data){
    alert(data)
    }
    </script>
    <script src="http://localhost:91?callback=f"></script>
    </body>
    </html>

、、、、、、

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信