用CORS模拟跨域

问起跨域,很多人都可以很轻松的说出JSONP(同源政策只限制XHR,而对于img,script的src没有限制,但是它只能通过get请求),CORS(服务器端设置)等等
但是,让其不看资料手写一遍估计够呛的。
比如我,今天尝试用CORS实现跨域,然而发现自己nodejs的早已忘完了。。

发起跨域请求的服务器代码:

const express = require("express");
const app = express();
const path = require("path")

app.use(express.static(path.join(__dirname, 'public')));
//拦截静态资源,为的就是页面能够顺利发送ajax请求
app.get('/',(req,res) => {
    console.log(111);
    res.header('Content-Type', 'text/html; charset=utf-8')
    res.end("我是Ajax请求过来的信息")
})
app.listen(3001);
console.log('服务器3001已开启');

发起跨域请求的页面:
注意:ajax得在服务器上请求才有效果,所以得通过localhost:3001/index1.html打开该页面,不能直接在本地文件打开,这里卡了我好久。。。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>点击发送Ajax实现跨域</button>
    <p>我是原始的信息</p>
    <script>
        const btn = document.querySelector("button");
        const  p = document.querySelector("p");
      
        btn.addEventListener("click",function(){
            let xhr = new XMLHttpRequest()
        xhr.open('get','http://localhost:3002')
        xhr.send()
       
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                console.log(xhr.responseText);
                p.innerText = xhr.responseText
            }
        }
        console.log(xhr);
        })
      
     
    </script>
</body>
</html>

接受跨域请求的信息

const express = require("express");
const app = express();
app.use((req,res,next) => {
    res.header("Access-Control-Allow-Origin","*")
    console.log(req.method,req.url);
    next()
})
app.get('/',(req,res) => {
    res.header('Content-Type', 'text/html; charset=utf-8')
    res.end("我是另一台服务器的信息")
})
app.listen(3002);
console.log('服务器3002已开启');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值