深刻跨域问题(1) - 初识 CORS 跨域资源共享;javascript
深刻跨域问题(2) - 利用 CORS 解决跨域(本篇)html
在阅读这篇文章以前,读读第一篇文章,效果会更好!!!回答上一篇文章的问题:node
application/x-www-form-urlencoded
。Content-Type
为 application/json
。并不是上文中的三种状况,text/plain
,multipart/form-data
,application/x-www-form-urlencoded
。第三点,是最重要的一点,也是常常出错的一点,记住触发预请求三种状况 !!!jquery
模拟客户端请求:ios
<!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
下载。ajax
模拟服务器响应,新建 app.js 文件,粘贴并运行 :npm
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 文件,就成了:json
很明显,这就是跨域报错。
在上述两个例子中,咱们说到,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
!!!
不单单是 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');
});
复制代码
执行结果:
预请求
POST 请求
这样就完成,对 预请求 的处理。如今你能够狠狠地告诉后台:是你没有处理 OPTIONS 方法 !!!
好了,到这里,知道了基础的 预请求 处理的解决办法了。
使用 CORS 跨域资源共享,是须要分红 预请求 与 非预请求 处理的。
非预请求,在服务器内,只须要简单设置:
'Access-Control-Allow-Origin': '* 复制代码
预请求,在服务器内,至少要设置三个 响应首部字段:
'Access-Control-Allow-Origin': ?,
'Access-Control-Allow-Methods': ?,
'Access-Control-Allow-Headers': 'Content-Type',
复制代码
前端使用 content-Type: application/json
的时候,必须注意这是 预请求 ,后端须要处理 OPTIONS 方法
祝你们编码愉快,喜欢的话点个赞再走呗!!!