HTTP(III)—— CORS跨域请求的限制与解决

一、首先添加一个html:

test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</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')
	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.end('123')
}).listen(8887)
console.log('server listening on 8887')

三、打开浏览器出入localhost:8888,然后会出现如下错误:显示没有设置Access-Control-Allow-Origin的头部

虽然有报错,但是请求已经发送,信息也已经返回,但是浏览器在解析这个返回内容后,发现是不允许的,然后报错。这是浏览器同域的限制。

四、我们在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('123')
}).listen(8887)
console.log('server listening on 8887')

然后去浏览的network查看会显示如下:

五、jsonp解决跨域。

我们修改test.html如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script src="http://127.0.0.1:8887/"></script>
</html>

修改server2.js如下:

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

此时重启服务去浏览器刷新,不会再报错,原因是浏览器允许img、script、link等标签在标签写路径内容,进行请求时,是允许跨域的。JSONP实现原理其实就在script标签里面加载了一个链接,这个链接去访问了服务器的内容,并且返回了响应的数据。

六、Access-Control-Allow-Origin头部的安全设置。

设置为*,是不安全的,这样任何域名都可以访问,我们该如何设置呢?

  • 可以设置为特定的域名,例如
'Access-Control-Allow-Origin': 'localhost:8888'
  • 动态的判断,通过获取到的request.url进行判断

猜你喜欢

转载自blog.csdn.net/zhanghuali0210/article/details/82079819