解决跨域请求

1.什么叫跨域共享

        跨源资源共享CORS,或通俗地译为跨域资源共享)是一种基于 HTTP 头的机制,该机制通过允许服务器标示除了它自己以外的其他(域、协议或端口),使得浏览器允许这些源访问加载自己的资源。跨源资源共享还通过一种机制来检查服务器是否会允许要发送的真实请求,该机制通过浏览器发起一个到服务器托管的跨源资源的“预检”请求。在预检中,浏览器发送的头中标示有 HTTP 方法和真实请求中会用到的头。

2.实例:

        以下为我练习时遇到的跨域问题,以及解决方法

        1.html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <label for="name">name</label><input type="text" name="" id="name">
    <label for="age">age</label><input type="password" id="age">
    <script src="./myaxios.js"></script>

    <script>
       const res = myAxios({url:"http://localhost:8081",method:"GET"});
       res.then((data)=>{
        console.log(data)
       })
    </script>
</body>
</html>

2.自我封装的ajax部分

function myAxios(config){
    return new Promise((resolve,reject)=>{
        const xhr = new XMLHttpRequest();
        if(config.params){
            const paramsobj = new URLSearchParams(config.params);
            const paramsStr = paramsobj.toString();
            config.url += `?${paramsStr}` ;
        }
        xhr.open(config.method||"GET",config.url);
        xhr.addEventListener("loadend",()=>{
            console.log("debugger:",xhr.status)
            if(xhr.status >=200&&xhr.status<=299) resolve(JSON.parse(xhr.response))
            else reject(new Error(xhr.response))
        })
        if(config.data){
            const jsonStr = JSON.parse(config.data);
            xhr.setRequestHeader("Content-type","")
            xhr.send(jsonStr)
        }else{
            xhr.send()
        }
    })
}

3.node.js部分

const http = require("http");
const server = http.createServer();

server.on("request", (req, res) => {
  if (req.method === "GET") {
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/html;charset=utf-8");
    res.end(JSON.stringify("welcome"));
  } else if (req.method === "POST") {
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json;charset=utf-8");
    res.end(JSON.stringify({ name: "llz", age: "11" }));
  }
});

server.listen(8081, () => {
  console.log("端口已开启");
});

其会报出一下错误

 

解决方案: 给响应头添加一下代码

res.setHeader("Access-Control-Allow-Origin", "*");// 此设置为允许所有与访问,不太安全,个人推荐修改为特定的域名
//如
res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");

完整版

const http = require("http");
const server = http.createServer();

server.on("request", (req, res) => {
  if (req.method === "GET") {
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/html;charset=utf-8");
    res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
    res.end(JSON.stringify("welcome"));
  } else if (req.method === "POST") {
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json;charset=utf-8");
    res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
    res.end(JSON.stringify({ name: "llz", age: "21" }));
  }
});

server.listen(8081, () => {
  console.log("端口已开启");
});

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值