跨域

85 阅读1分钟

产生跨域的原因

由浏览器的同源策略造成的

同域名,同端口,同协议(http 和 https)

跨域解决方案1

ORS跨域资源共享
服务端:header("Access-Control-Allow-Origin:*");
“*”表示所有的域都可以接受

跨域解决方案2

 jsonp
    动态创建script标签,使用jQuery的jsonp请求
    优点
    兼容性强&不受同源策略的限制
    缺点
    只能用get方法,不能使用post方法
script src="./jquery-1.12.4.js"></script>
     <script>
         /* 使用jsonp解决跨域 */
        $.ajax({
            url:"http://192.168.1.2/a.php",
            type:"get",
            //定义发送jsonp请求
            dataType:'jsonp',
            //更改定义的参数名
            jsonp:'kyFn',//修改callback名称,但是php中也要修改成相对应的函数名
            //指定jsonp发送的回调函数名(可以任意起名字,无需对应)
            // jsonpCallback:'callBack',
            success:function (res){
                document.write(res);
            }
        });
        // function callBack(res){
        //     document.write(res);
        // }


        //  $.ajax({
        //     url:"http://localhost:3000",
        //     success:function(res){
        //         console.log(res);
        //     },
        //     error:function(err){
        //         console.log(err)
        //     }
        //  })
     </script>

a.php

<?php
	header("Content-type: text/html;charset=utf-8");
	$callback=$_GET['kyFn'];
	echo $callback.'("涛涛很帅 很有money")';
?>

server.js

let http = require('http')
http.createServer((req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','*')
    res.end('success')
}).listen(3000,function(){
    console.log('server start...')
})