zoukankan      html  css  js  c++  java
  • CORS跨域

    跨域是指在浏览器客户端,产生的行为。在curl客户端不存在跨域。

    浏览器跨域案例展示:

    server.js

    const http = require('http')
    const fs = require('fs')
    
    http.createServer((req, res) => {
      console.log('request come', req.url)
    
      const html = fs.readFileSync('test.html', 'utf8')
      res.writeHead(200, {
        'Content-Type': 'text/html'
      })
      res.end(html)
    
    }).listen(8888)
    
    console.log('server listening on 8888')

    test.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
    <script>
      var xhr = new XMLHttpRequest()
      xhr.open('GET', 'http://127.0.0.1:8887/')
      xhr.send()
    </script>
    </body>
    </html>

    node server.js后,访问 http://localhost:8888/

       因为http://127.0.0.1:8887 的响应头里,没有允许http://127.0.0.1:8888请求数据。所以根据同源政策,浏览器将http://127.0.0.1:8887的响应数据屏蔽了。

    当我们在8887的响应头里允许8888访问后,浏览器就会将响应内容解锁。

    服务端解决跨域:

    server2.js

    const http = require('http')
    
    http.createServer((req, res) => {
      console.log('request come', req.url)
    
      res.writeHead(200, {
        'Access-Control-Allow-Origin': '*'
      })
      res.end('123')
    }).listen(8887)
    
    console.log('server listening on 8887')

    这里的 'Access-Control-Allow-Origin': '*' 是指允许所以的地址访问。

    允许指定的地址访问可以这么写 'Access-Control-Allow-Origin': 'http://127.0.0.1:8888'   'Access-Control-Allow-Origin': 'http://baidu.com' 

    jsonp解决跨域:[原理: 浏览器允许link标签、script标签、img标签等,跨域加载数据]

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
    <!-- <script>
      var xhr = new XMLHttpRequest()
      xhr.open('GET', 'http://127.0.0.1:8887/')
      xhr.send()
    </script> -->
    <script src="http://127.0.0.1:8887/"></script>
    </body>
    </html>
  • 相关阅读:
    linux命令(一)
    Maven 打包不同环境
    Spring动态代理
    Spring MVC controller方法和jstl
    logback的使用
    从文本导入导出
    将临时全局表中的符合字段导入test数据库中
    将上传的新表导入临时全局表中
    建立临时表导入
    查询统计表以及删除表
  • 原文地址:https://www.cnblogs.com/ladybug7/p/12334460.html
Copyright © 2011-2022 走看看