目录结构
文件内容
server1.js
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
console.log('request come', req.url);
const html = fs.readFileSync('index.html', 'utf8');
res.writeHead(200, {
// "Content-Type":"text/plain"
"Content-Type":"text/html"
})
res.end(html)
}).listen(8888)
console.log('server start at port 8888')
server2.js
const http = require('http');
http.createServer(function(req, res) {
console.log('request come', req.url);
res.writeHead(200, {
// 'Access-Control-Allow-Origin':"*"
// 'Access-Control-Allow-Origin':"http://localhost:8887"
'Access-Control-Allow-Origin':"http://localhost:8888"
})
res.end('123')
}).listen(8889)
console.log('server start at port 8889')
index.html
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
8888
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET','http://127.0.0.1:8889');
xhr.send();
</script>
</body>
</html>
配置解析
返回的文本类型
"Content-Type":"text/plain" //字符串
"Content-Type":"text/html" //html
server2.js
不配置Access-Control-Allow-Origin
- 会请求,有响应
- 浏览器特有,只是浏览器出于安全,不显示内容
- 在git bash上会显示内容
res.writeHead(200, {
// 'Access-Control-Allow-Origin':"*" //允许所有
// 'Access-Control-Allow-Origin':"http://localhost:8887"
// 'Access-Control-Allow-Origin':"http://localhost:8888"
})
配置Access-Control-Allow-Origin
'Access-Control-Allow-Origin':"*" //允许所有
'Access-Control-Allow-Origin':"http://localhost:8887" //允许特定
jsonp
利用标签的特性
- link
- img
- script
index.html
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
8888
<script src='http://127.0.0.1:8889'></script>
</body>
</html>
server2.js
const http = require('http');
http.createServer(function(req, res) {
console.log('request come', req.url);
res.writeHead(200, {
})
res.end('123')
}).listen(8889)
console.log('server start at port 8889')
cors其它配置
默认允许方法
- GET
- HEAD
- POST
当用put方法时
index.html
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
8888
<script>
var xhr = new XMLHttpRequest();
xhr.open('PUT','http://127.0.0.1:8889');
xhr.send();
</script>
</body>
</html>
解决办法
res.writeHead(200, {
'Access-Control-Allow-Origin':"*",
"Access-Control-Allow-Methods":"GET,POST,PUT,DELETE"
})
预请求
解决办法
res.writeHead(200, {
'Access-Control-Allow-Origin':"*",
"Access-Control-Allow-Methods": "GET,POST,PUT,DELETE",
"Access-Control-Allow-Max-Age":"1000",
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。