跨域 (2) cors

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>cors例子</title>
</head>
<body>
<script>
   var xmlhttp;
    if (window.XMLHttpRequest)
    {
        //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // IE6, IE5 浏览器执行代码
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            console.log(xmlhttp)
        }
    }
    xmlhttp.open("GET","http://localhost:3000/get",true);
    xmlhttp.send();

</script>
</body>
</html>

我们创建一个ajax 请求接口 端口为3000

后端的端口为4000

server.js

const express = require('express');
const app = express();
app.get('/get',function(req,res) {
       res.end('跨域处理')
})
app.listen(3000, () => console.log('The server is starting at port 3000'));

产生跨域:

 

添加跨域处理:

app.all('*', function (req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
      res.header('Access-Control-Allow-Headers', 'Content-Type');
      res.header('Access-Control-Allow-Methods', '*');
      res.header('Content-Type', 'application/json;charset=utf-8');
      next();
    });

  效果:

输出;跨域处理

 

 

 

仓库地址:https://gitee.com/guangzhou110/web-attack

转载于:https://www.cnblogs.com/guangzhou11/p/11619182.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值