<!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>
</body>
<script>
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://127.0.0.1:8887/')
xhr.send()
</script>
</html>
server.js
const http = require('http')
const fs = require('fs')
http.createServer(function (request, response) {
console.log('request come', request.url)
const html = fs.readFileSync('test.html', 'utf8')//读取HTML内容
response.writeHead(200, {
'Content-Type': 'text/html'
})
response.end(html)
}).listen(8888)
console.log('server listening on 8888')
server2.js
const http = require('http')
http.createServer(function (request, response) {
console.log('request come', request.url)
response.writeHead(200, {
'Access-Control-Allow-Origin': '*'
//'Access-Control-Allow-Origin': 'http://127.0.0.1:8888'//指定域名可以访问
/*浏览器已经发送,并且数据也已经返回,只是浏览器在解析返回的内容的时候发现是不允许的,
浏览器帮你拦截掉了*/
})
response.end('123')
}).listen(8887)
console.log('server listening on 8887')
本文探讨了CORS(跨源资源共享)在Web开发中对跨域请求的限制,以及如何通过设置服务器响应头来解决这些限制。通过分析`server.js`和`server2.js`示例代码,揭示了允许特定来源、处理预检请求(OPTIONS)等关键策略。
2万+

被折叠的 条评论
为什么被折叠?



