美文网首页HTTP协议原理+实践
3-2 CORS跨域请求的限制与解决

3-2 CORS跨域请求的限制与解决

作者: 伯纳乌的追风少年 | 来源:发表于2018-11-30 09:56 被阅读0次
服务器8888:
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')
  response.writeHead(200,{
    'Content-Type':'text/html'
  })
  response.end(html)
}).listen(8888)
console.log('server listening on 8888')
服务器8887:
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')
发起跨域请求的页面test.html
<html>
<head>
  <title>CORS跨域请求的限制与解决</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>

</body>
<script type="text/javascript">
  // var xhr=new XMLHttpRequest()
  // xhr.open('GET','http://127.0.0.1:8887')
  // xhr.send()
</script>
<!-- JSONP方法 -->
<script src="http://127.0.0.1:8887"></script>
</html>
由8888加载test.html,跨域成功向8887发送请求:

相关文章

网友评论

    本文标题:3-2 CORS跨域请求的限制与解决

    本文链接:https://www.haomeiwen.com/subject/zuubqqtx.html