当前位置: 首页 > 后端技术 > Node.js

跨域_0

时间:2023-04-03 19:21:28 Node.js

1、JSONP的基本原理是动态创建script标签,然后利用src属性跨域(后端可以用回调函数名包裹数据返回),但需要注意的是JSONP只支持GET请求,不支持POST请求//回调函数functionshowData(result){//json对象转为字符串$('#text').val(JSON.stringify(result));}$(document).ready(function(){$('#btn').click(function(){//向head输入一个脚本,脚本发起跨域请求$('head').append('');});});jQuery的JSONP请求$(document).ready(function(){$('#btn').click(function(){$.ajax({url:'http://localhost:9090/student',type:'GET',dataType:'jsonp',//指定服务器返回的数据类型jsonpCallback:'showData',//也可以指定回调函数success:function(data){//将json对象转为字符串$('#text').val(JSON.stringify(data));}});});});二、CORS跨域资源共享使用nginx或php、java等后台语言设置允许跨域请求:header('Access-Control-Allow-Origin:*');//允许所有源访问header('Access-Control-Allow-Method:POST,GET');//允许访问的方式3.服务器代理浏览器有跨域限制,但是服务器不存在域问题,所以服务器可以请求想要的域的资源,返回给客户端。Nodejs作为代理(eggjs)asyncdemo(){const{ctx:{inputs}}=this;//第三方接口地址consturl='http://api.map.baidu.com/location/ip';//获取第三方接口constres=awaitthis.ctx.curl(url,{method:'POST',dataType:'text',data:inputs});//返回数据this.success({data:res.data~~~~});}四、Nginx反向代理在配置文件nginx.conf中添加如下配置:location/{add_headerAccess-Control-Allow-Origin*;add_headerAccess-Control-Allow-Methods'GET,POST,OPTIONS';add_headerAccess-Control-Allow-Headers'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';如果($request_method='OPTIONS'){返回204;}}更多文章Github对掘金的思考