CORS 跨域请求 - 1

    xiaoxiao2023-10-04  36

    首先我们来写两个简单的服务器:

    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') response.writeHead(200, { 'Content-Type': 'text/html' }) response.end(html) }).listen(8888) console.log('serve listening on 8888')

    test.html 如下,它请求8887端口

    <!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>MyHtml</title> </head> <body> <div>hello world</div> <div>don't speak</div> <script> var xhr = new XMLHttpRequest() xhr.open('GET', 'http://127.0.0.1:8887/') xhr.send() </script> </body> </html>

    server2.js 如下

    const http = require('http') http.createServer(function (request, response) { console.log('request come', request.url) response.end('12345') }).listen(8887) console.log('serve listening on 8887')

    然后我们把他们都启动.

    当我们访问127.0.0.1:8888 时,它会向 127.0.0.1:8887 发送一个ajax 请求。这个请求就是跨域的请求。

    显然这时候,会报错,如下

    它提示 'Access-Control-Allow-Origin' 头没有被设置,而这个就是服务端允许跨域的header 。

    那我们可以去设置一下:

    server2.js

    const http = require('http') http.createServer(function (request, response) { console.log('request come', request.url) response.writeHead(200, { 'Access-Control-Allow-Origin': '*' }) response.end('12345') }).listen(8887) console.log('serve listening on 8887')

    重启server2.js ,刷新之前的网页,发现可以正确发送ajax 请求,同时也返回了‘12345’.

    实际上当没有设置 'Access-Control-Allow-Origin' 时,浏览器也会发送ajax 请求到指定的地址(‘request come’ 打印出来了),但是,在返回的头中,浏览器没有找到 'Access-Control-Allow-Origin' 为‘*’ 时,就会自动忽略这个请求返回的内容,同时在命令行中报错。

    因此,同源策略实际上,只是浏览器的策略。在curl 中,则没有这个限制。curl 任何发送的请求都是可以发送到并返回输出的(正确情况下)。

    header 中  'Access-Control-Allow-Origin' 为 ‘*’ 。表示任何域名的页面,都可以访问这个服务。因此这个是非常不安全的!我们可以改为:(在浏览器中需要把url 中 localhost 改为127.0.0.1 )

    response.writeHead(200, { // 'Access-Control-Allow-Origin': '*' 'Access-Control-Allow-Origin': 'http://127.0.0.1:8888' })

    除了在服务器端设置 ‘Access-Control-Allow-Origin’ ,还可以通过JSONP的方式解决跨域问题。JSONP 就是在script 标签中使用src 。如下。

    <!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>MyHtml</title> </head> <body> <div>hello world</div> <div>don't speak</div> <script src="http://127.0.0.1:8887/"> </script> </body> </html>

     

    最新回复(0)