一、跨域分析
1、什么是跨域请求?
由于浏览器同源策略,凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。在Ajax中,表现为浏览器请求url和nodels开启的server服务中host和port不一致。如下图所示:
2、跨域问题分析
造成跨域访问受限的原因是浏览器中同源策略机制。
如果url中端口(如果有指定)和域名都相同,则他们具有相同的源
如果url中端口(如果有指定)和域名有差别,则他们属于不同的源
在发送Ajax请求时,浏览器就会对跨域的请求做出限制
二、跨域案例
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--http通过from请求数据-->
<!--<form action="http://127.0.0.1:8080" method="get">-->
<!--<input type="submit" value="提交" id="ajaxBtn">-->
<!--</form>-->
<!--ajax请求数据-->
<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自身浏览器造成的跨域问题。
2)请求url(http://localhost:8080/)不同造成的跨域问题。
三、跨域解决方案
在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
<script>
function fn(data){
console.log(data)
}
window.onload=function () {
const ajaxBtn = document.querySelector("#ajaxBtn");
ajaxBtn.addEventListener("click",(ev)=>{
ev = ev||event;
const scriptNode = document.createElement("script");
scriptNode.src="http://127.0.0.1:8080/ky"
document.body.appendChild(scriptNode);
ev.preventDefault();
})
}
</script>
如上所示:
html添加如下数据处理代码并告诉服务端:
function fn(data){
console.log(data)
}
server响应:
response.end(`fn("123")`);
测试结果:
3、CORS——Access-Control-Allow-Origin
1)原理:Access-Control-Allow-Origin 响应头指定了该响应的资源是否被允许与给定的origin共享。
2)语法:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>
参数 origin
origin:指定一个可以访问资源的URI
origin
请求首部字段 Origin 指示了请求来自于哪个站点。
3)实现
if(requestMsg.url === "/ky"){//cors
let corsUrl = "";
if(requestMsg.headers["origin"] === "http://127.0.0.1:63342"){
corsUrl = "http://127.0.0.1:63342";
}else if(requestMsg.headers["origin"] === "http://localhost:63342"){
corsUrl = "http://localhost:63342";
}
response.writeHead(200,"OK",{
"Content-type":"application/x-javascript",
"Access-Control-Allow-Origin":corsUrl,
})
response.end("123");
}
4)CORS优化——预请求验证
本质上在跨域处理这一块,CORS还有一些其他的设置。
允许的http方法:
除了GET HEAD POST外其他方法是不允许的
请求头的限制:
自定义请求体是不允许的。
实现方案
Access-Control-Allow-Headers:
响应首部 Access-Control-Allow-Headers 用于预检请求,代表允许跨域的请求头
Access-Control-Allow-Methods:
响应首部 Access-Control-Allow-Methods用于预检请求,代表允许跨域的http方法
Access-Control-Max-Age:
The Access-Control-Max-Age 这个响应首部表示预检请求的返回结果(即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息) 可以被缓存多久
5)代码实现:
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"){//cors
let corsUrl = "";
if(requestMsg.headers["origin"] === "http://127.0.0.1:63342"){
corsUrl = "http://127.0.0.1:63342";
}else if(requestMsg.headers["origin"] === "http://localhost:63342"){
corsUrl = "http://localhost:63342";
}
response.writeHead(200,"OK",{
"Content-type":"application/x-javascript",
"Access-Control-Allow-Origin":corsUrl,
})
response.end("123");
}else if(requestMsg.url === "/cors"){//cors优化,加入预请求验证
let corsUrl = "";
if(requestMsg.headers["origin"] === "http://127.0.0.1:63342"){
corsUrl = "http://127.0.0.1:63342";
}else if(requestMsg.headers["origin"] === "http://localhost:63342"){
corsUrl = "http://localhost:63342";
}
response.writeHead(200,"OK",{
"Content-type":"application/x-javascript",
"Access-Control-Allow-Origin":corsUrl,
"Access-Control-Allow-Headers":"zd",
"Access-Control-Allow-Methods":"PUT,DELETE",
"Access-Control-Max-Age":"10"
})
response.end("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
<body>
<!--http通过from请求数据-->
<form action="http://127.0.0.1:8080" method="get">
<input type="submit" value="提交" id="ajaxBtn">
</form>
</body>
<script>
window.onload=function () {
const ajaxBtn = document.querySelector("#ajaxBtn");
ajaxBtn.addEventListener("click", (ev) => {
ev = ev || event;
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
alert(xhr.responseText)
console.log(xhr.responseText);
}
}
}
xhr.open("GET", "http://127.0.0.1:8080/cors");
xhr.send();
ev.preventDefault();
})
}
</script>
6)测试结果:
4、Nginx反向代理