深入跨域问题(2) - 利用 CORS 解决跨域

目录

1.搭建跨域环境(先展示一下跨域请求的情况):

2.处理非预请求

3.处理 POST 预请求

4.总结:


1.搭建跨域环境(先展示一下跨域请求的情况):

模拟客户端请求:

<!DOCTYPE html>
<html lang="zh-CN">
<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>Ajax测试</title>
</head>
<body>
    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
    <script>
        $.ajax({
            url: "http://localhost:3000",
            type: "get",
            success: function (result) {
                console.log(result);
            },
            error: function (msg) {
                console.log(msg);
            }
        })
    </script>
</body>
</html>

后文,将不再粘贴 html 代码,jquery 也可以用 npm install jquery 下载。

模拟服务器响应,新建 app.js 文件,粘贴并运行 :

const http = require('http');

const server = http.createServer((request, response) => {
    if (request.url === '/') {
        if (request.method === 'GET') {
            response.end("{name: 'BruceLee', password: '123456'}");
        }
        
        if (request.method === 'POST') {
            response.end("true");
        }
    }

    response.end('false');
});

server.listen(3000, () => {
    console.log('The server is running at http://localhost:3000');
});

好了,现在双击打开 html 文件,就成了:

很明显,这就是跨域报错。

2.处理非预请求

在上述两个例子中,我们说到,POST 和 GET 方法,都可以实现,非预请求。

关键代码:设置一条 响应首部字段,允许 CORS 跨域资源共享:

response.writeHead(200, {
  'Access-Control-Allow-Origin': '*
}

这里,我们设置为,所有客户端都可以访问。

完整代码:

const http = require('http');

const server = http.createServer((request, response) => {
    if (request.url === '/') {
        if (request.method === 'GET') {
            
            response.writeHead(200, {
                'Access-Control-Allow-Origin': '*' // 关键代码
            });
            
            response.end("{name: 'BruceLee', password: '123456'}");
        }
        
        if (request.method === 'POST') {
            
            response.writeHead(200, {
                'Access-Control-Allow-Origin': '*' // 关键代码
            });
            
            response.end("true");
        }
    }

    response.end('false');
});

server.listen(3000, () => {
    console.log('The server is running at http://localhost:3000');
});

前端测试代码:

$.ajax({
    url: "http://localhost:3000",
    type: "get",
    success: function (result) {
        console.log(result);
    },
    error: function (msg) {
        console.log(msg);
    }
})


var data = { name: 'BruceLee', password: '123456' };

$.ajax({
    url: "http://localhost:3000",
    type: "post",
    data: JSON.stringify(data),
    success: function (result) {
        console.log(result);
    },
    error: function (msg) {
        console.log(msg);
    }
})

执行结果:

处理 非预请求 就是这么简单,只需要在后台设置,一条 响应首部字段 即可。

注意:我们使用 POST 方法时,Jquery 默认使用的 Content-Type: application/x-www-form-urlencoded,所以不会触发预请求 !!!

事实上,不仅仅是 Jquery ,axios 等封装 Ajax 的库,都默认采用 Content-Type: application/x-www-form-urlencoded !!!

3.处理 POST 预请求

不仅仅是 POST ,所有 预请求 的处理方式都一样。

POST 方法在设置 contentType 为 application/json 时会触发预请求。

前端测试代码:

var data = { name: 'BruceLee', password: '123456' };

$.ajax({
    url: "http://localhost:3000",
    type: "post",
    data: JSON.stringify(data),
    contentType: 'application/json;charset=utf-8',
    success: function (result) {
        console.log(result);
    },
    error: function (msg) {
        console.log(msg);
    }
})

注意,这里的 contentType 已经修改为 application/json ,这种情况是会触发 预请求 的 ! ! !

node 服务端代码:

const http = require('http');

const server = http.createServer((request, response) => {
    if (request.url === '/') {
        if (request.method === 'GET') {
            response.writeHead(200, {
                'Access-Control-Allow-Origin': '*'
            });
            response.end("{name: 'BruceLee', password: '123456'}");
        }

        if (request.method === 'POST') {
            response.writeHead(200, {
                'Access-Control-Allow-Origin': '*'
            });

            response.end( JSON.stringify({state: true}) );
        }

        if (request.method === 'OPTIONS') {	
    		
            response.end( JSON.stringify({state: true}) );
        }
    }

    response.end('false');
});

server.listen(3000, () => {
    console.log('The server is running at http://localhost:3000');
});

在这里,我们增加了处理 OPTIONS 方法的逻辑。

测试结果:

很明显,我们在 OPTIONS 方法内部没有设置 CORS 响应首部字段 ,所以出现跨域错误;

修改代码,关键代码:

if (request.method === 'OPTIONS') {	
    response.writeHead(200, {
        'Access-Control-Allow-Origin': '*',	 // 设置 optins 方法允许所有服务器访问 
        'Access-Control-Allow-Methods': '*', // 允许访问 POST PUT DELETE 等所有方法 
    });		
    response.end( JSON.stringify({state: true}) );
}

在 node 代码中,我们增加对 OPTIONS 的处理,并且设置允许访问, POST 方法。

修改代码后,重启服务器,并刷新 html 页面,结果为:

在这里,仍然是有问题,按照报错描述,我们应该设置 Access-Control-Allow-Headers 响应首部字段 。

关键代码:


if (request.method === 'OPTIONS') {	
    response.writeHead(200, {
        'Access-Control-Allow-Origin': '*',	 // 设置 optins 方法允许所有服务器访问 
        'Access-Control-Allow-Methods': '*', // 允许访问路径 '/' POST等所有方法
        'Access-Control-Allow-Headers': 'Content-Type',	// 允许类 Content-Type 头部 
    });	
    response.end( JSON.stringify({state: true}) );
}

 我们需要设置,允许使用头部为 Content-Type 的内容访问。

完整代码:

const http = require('http');

const server = http.createServer((request, response) => {
    if (request.url === '/') {
        if (request.method === 'GET') {
            response.writeHead(200, {
                'Access-Control-Allow-Origin': '*'
            });
            response.end("{name: 'BruceLee', password: '123456'}");
        }

        if (request.method === 'POST') {
            response.writeHead(200, {
                'Access-Control-Allow-Origin': '*'
            });

            response.end( JSON.stringify({state: true}) );
        }

        if (request.method === 'OPTIONS') {	
            response.writeHead(200, {
                'Access-Control-Allow-Origin': '*',	 // 设置 optins 方法允许所有服务器访问 
                'Access-Control-Allow-Methods': '*', // 允许访问路径 '/' POST等所有方法
                'Access-Control-Allow-Headers': 'Content-Type',	// 允许类 Content-Type 头部 
            });
        }
    }

    response.end('false');
});

server.listen(3000, () => {
    console.log('The server is running at http://localhost:3000');
});

执行结果:

  1. 预请求

2.POST 请求

这样就完成,对 预请求 的处理。现在你可以狠狠地告诉后台:是你没有处理 OPTIONS 方法 !!!

好了,到这里,知道了基础的 预请求 处理的解决办法了。 

4.总结:

  1. 使用 CORS 跨域资源共享,是需要分成 预请求 与 非预请求 处理的。

  2. 非预请求,在服务器内,只需要简单设置:

'Access-Control-Allow-Origin': '*

    3.预请求,在服务器内,至少要设置三个 响应首部字段

'Access-Control-Allow-Origin': ?,	  
'Access-Control-Allow-Methods': ?, 
'Access-Control-Allow-Headers': 'Content-Type',

4.前端使用 content-Type: application/json 的时候,必须注意这是 预请求 ,后端需要处理 OPTIONS 方法

猜你喜欢

转载自blog.csdn.net/m0_68997646/article/details/128751178