CORS跨域请求的限制与解决

本文探讨了CORS(跨源资源共享)在Web开发中对跨域请求的限制,以及如何通过设置服务器响应头来解决这些限制。通过分析`server.js`和`server2.js`示例代码,揭示了允许特定来源、处理预检请求(OPTIONS)等关键策略。
<!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')
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值