跨域问题
因浏览器提供的安全机制,两个不同源的客户端、服务端的交互可能会产生跨域问题(即协议、域名、端口有一个不同就会引起)。
demo.html为资源请求方。
server.js为资源提供方。
以上图片,已经以JSONP的方式解决了跨域问题。
跨域问题的解决
CORS:只需在服务端的响应头设置’Access-Control-Allow-Origin’:’*’ 就行,即允许所有地址访问服务端资源。
JSONP:script元素本身是不受同源策略的制约的。那么可以以JSONP的方式解决。什么是JSONP?就是将JSON数据封装在函数里返回给前端调用执行。
JSONP解决方式代码(Node.js)
前端代码
<!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>
let jsonpcallback;
const url='http://localhost:3000/data';
function getJSONP(url, callback) {
url+='?callback=jsonpcallback';
let script = document.createElement('script');
script.type='text/javascript';
script.src = url;
document.body.appendChild(script);
jsonpcallback =function(response) {
try {
callback(response);
} finally {
script.parentNode.removeChild(script);
}
}
}
getJSONP(url,function(response){
console.log(response);
});
</script>
</body>
</html>
服务端代码
const http = require('http');
const { rawListeners } = require('process');
const qs = require('querystring');
http.createServer(function (req, res) {
if ('/data' === req.url.substr(0,5)) {
let post = {
result: '成功',
name:'lihua'
}
res.writeHead(200, {
'Content-Type': 'text/javascript',
// 'Access-Control-Allow-Origin':'*'
});
let obj = req.url.substr(req.url.indexOf('?') + 1).split('=');
console.log(obj[1] + '(' + JSON.stringify(post) + ')');
res.end(obj[1] + '(' + JSON.stringify(post) + ')');
} else {
res.writeHead(404, {
'Context-Type': 'text/plain'
});
res.end('404\n页面不存在');
}
}).listen(3000);