解决跨域的几种方式

258 阅读1分钟

以下是几种常见的跨域请求方式;

jsonp

addBtn.onclick=function(){
    var script=document.createElement("script");//创建一个script标签
    script.src="url?cb=fn";
    document.body.appendChild(script);
    document.body.removeChild(script);
}
function fn(data){
    alert(data.msg);
}

服务器作为中转

前端请求:

<script>
    var xhr=new XMLHttpRequest();
    xhr.open("get","/heihei")   //访问自己的服务器
    xhr.send()
    xhr.onload=function(){
        if(xhr.status===200){
            var obj=JSON.parse(xhr.responseText)
            console.log(obj)
    }
}
</script>

中间层(以node.js为例)

const express=require("express")
const request=require("request")
const bodyParse=require("body-parser");
const app=express();
app.use(bodyParse.json())
app.all("*",function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    next();
})
app.get("/heihei",function(req,res){
    request("url",function(err,response,body){   //结果在body中
    res.json(
        JSON.parse(body)
    )
})
app.listen(80,function(){
    console.log("服务开启成功")
})

服务端允许跨域请求

app.all("*",function(req,res,next){
//设置响应的头部信息,允许所有域名跨域请求
//当请求的证书模式为“include”时,不能设置为*,需要写具体域名
res.header("Access-Control-Allow-Origin","*");
//支持哪些响应方式
res.header("Access-Control-Allow-Methods","POST,PUT,GET,OPTIONS,DELETE");
// 响应头支持content-type
res.header("Access-Control-Allow-Headers","content-type");
next();
})

总结

现在一般跨域请求的方式一般都是后端允许跨域请求,不需要前端过多的进行处理