跨域问题的解决

跨域问题

因浏览器提供的安全机制,两个不同源的客户端、服务端的交互可能会产生跨域问题(即协议、域名、端口有一个不同就会引起)。

在这里插入图片描述

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值