NodeJs中Ajax跨域问题分析

一、跨域分析

1、什么是跨域请求?

由于浏览器同源策略,凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。在Ajax中,表现为浏览器请求url和nodels开启的server服务中host和port不一致。如下图所示:
NodeJs中Ajax跨域问题分析_第1张图片
2、跨域问题分析

造成跨域访问受限的原因是浏览器中同源策略机制。

如果url中端口(如果有指定)和域名都相同,则他们具有相同的源
如果url中端口(如果有指定)和域名有差别,则他们属于不同的源
在发送Ajax请求时,浏览器就会对跨域的请求做出限制

NodeJs中Ajax跨域问题分析_第2张图片
NodeJs中Ajax跨域问题分析_第3张图片

二、跨域案例

1、跨域的实例代码

server.js

const http = require("http")
const config = require("../config/config")
const fs = require("fs");
const server = http.createServer((requestMsg,response)=>{
    if(requestMsg.url === "/"){
        fs.readFile("./html/ajax.html",(err,data)=>{
            response.writeHead(200,"OK",{
                "Content-type":"text/html",
            })
            response.end(data);
        })
    }else if(requestMsg.url === "/?"){
        response.writeHead(200,"GET",{
            "Content-Type": "text/html; charset=utf-8"
        })
        response.end("处理GET请求");
    }else{
        response.writeHead(500, "Invalid Request", {"Content-Type": "text/html; charset=utf-8"});
        response.end("无效请求");
    }
})

server.listen(config.port,config.host,()=>{
    console.log(`server starting at ${config.host}:${config.port}`)
})

ajax.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>


    



<form >
    <input type="submit" value="提交" id="ajaxBtn">
form>
body>
<script>

    window.onload = ()=>{
        const ajaxBtn = document.querySelector("#ajaxBtn");
        ajaxBtn.addEventListener("click",(ev)=>{
            ev = ev||event;
            ev.preventDefault();
            makeRequest("GET","http://127.0.0.1:8080")
        })

        function makeRequest(method,url) {
         const   httpRequest = new XMLHttpRequest();

            if (!httpRequest) {
                alert('Giving up :( Cannot create an XMLHTTP instance');
                return false;
            }
            httpRequest.onreadystatechange =()=>{
                if (httpRequest.readyState === XMLHttpRequest.DONE) {
                    if (httpRequest.status === 200 || httpRequest.status === 304) {
                        alert(httpRequest.responseText);
                        console.log(httpRequest.responseText)
                    } else {
                        alert('There was a problem with the request.');
                    }
                }
            };

            httpRequest.open(method,url);
            httpRequest.send();
        }


    }

script>
html>

2、跨域问题表现:

1)使用webstorm自身浏览器造成的跨域问题。
NodeJs中Ajax跨域问题分析_第4张图片
2)请求url(http://localhost:8080/)不同造成的跨域问题。
NodeJs中Ajax跨域问题分析_第5张图片

三、跨域解决方案

在web开发中,当使用第三方框架时,不可避免要出现跨域问题。那么如何解决跨域访问受限?提供以下四种方案参考。

1、如果可以同时控制前后端,可以通过控制域名来解决跨域。不推荐。

server.listen(config.port,config.host,()=>{//nodojs开启的服务
    console.log(`server starting at ${config.host}:${config.port}`)
})

//客户端请求url
makeRequest("GET","http://127.0.0.1:8080")

2、jsonp——JSON width Padding(非官方的跨域解决方案)
原理:利用script标签中的src是不会受同源策略限制的特点来完成跨域请求。
此种方案由前端发起,后端配合。
server.js的代码:

const http = require("http")
const config = require("../config/config")
const fs = require("fs");
const server = http.createServer((requestMsg, response) => {

    if (requestMsg.url === "/") {
        fs.readFile("./html/ajax.html", (err, data) => {
            response.writeHead(200, "OK", {
                "Content-type": "text/html",
            })
            response.end(data);
        })
    } else if (requestMsg.url === "/ky") {
        response.writeHead("200", "OK", {
            "Content-type": "application/x-javascript;charset=utf-8"
        })
        //利用script标签中的src是不会受同源策略限制的特点来完成跨域请求。
        response.end(`fn("123")`);

    } else if (requestMsg.url === "/?") {
        response.writeHead(200, "GET", {
            "Content-Type": "text/html; charset=utf-8"
        })
        response.end("处理GET请求");
    } else {
        response.writeHead(500, "Invalid Request", {"Content-Type": "text/html; charset=utf-8"});
        response.end("无效请求");
    }
})

server.listen(config.port, config.host, () => {
    console.log(`server starting at ${config.host}:${config.port}`)
})

ajax.html


                    
                    

你可能感兴趣的:(NodeJs中Ajax跨域问题分析)