当前位置:网站首页>5.nodejs--cross domain, CORS, JSONP, Proxy

5.nodejs--cross domain, CORS, JSONP, Proxy

2022-08-02 03:15:00 love bubble tea

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


1.跨域

(1.1) Basic concepts of cross-domain

 (1)概念:The browser protects the user's information,There is a web request technique in web pages:ajaxwhen making network requests,The requested URL and the current page's URL are not on the same server,就会被拒绝.
        Two conditions across domains:非同源 ajax

什么是同源策略
==>浏览器的一种安全策略,Refers to the agreement between two URLs ip port All three represent the same origin

//同源==>pathnameDoes not participate in homology judgment
http://www.baidu.com/index.html
http://www.baiud.com/home/goods/ajax1

//异源 ==>域名(ip:port)不一样
http://www.hqyj.com/index.html
http://www.hqyj.con/ajax

//异源 ==>域名(ip:port)不一样
http://www.hqyj.com/index.html //假设解析DNS为192.168.6.86:8000
http://192.168.6.86:8000/ajax

(1.2) 接口的跨域问题

1.主要有两种方案:
        CORS(主流的解决方案,推荐使用)
        JSONP(有缺陷的解决方案:只支持GET请求)

    
2.使用cors中间件解决跨域问题
       使用步骤分为如下三步:
            (1) 运行npm install cors安装中间件
            (2) 使用const cors=require("cors")导入中间件
            (3) 在路由之前调用app.use(cors())配置中间件

2.CORS

(2.1)什么是cors

  (1) 什么是cors?
     ==>   cors(跨域资源共享)由一系列http响应头组成,这些http响应头决定浏览器是否阻止前端js代码跨域获取资源
        浏览器的同源安全策略默认会阻止网页“跨域”获取资源,但如果接口服务器配置了cors相关的http响应头,就可以解除浏览器端的跨域访问限制.

cors的注意事项:
           (1) cors主要在服务器端进行配置,客户端浏览器无须做任何额外的配置,即可请求开启了cors的接口
            (2)corsCompatibility in browsers,只有支持XMLHttpRequest Level2的浏览器,才能正常访问开启了cors的服务器端接口.

(2.2) CORS跨域资源共享--CORSof the three response headers

(1)CORS响应头部--Access-Control-Allow-Origin

 (1) CORS响应头部--Access-Control-Allow-Origin
    Carry one in the response headerAccess-Control-Allow-Origin字段,

        语法:Access-Control-Allow-Origin:<Origin>|*
    Origin参数的值指定了允许访问该资源的外域URL
   

 例如:下面的字段值将只允许来自http://itcast.cn的请求:
        res.setHeader('Access-Control-Allow-Origin','http://itcast.cn') 

(2)CORS响应头部--Access-Control-Allow-Headers  

 (2) CORS响应头部--Access-Control-Allow-Headers
        默认情况下,CORS仅支持客户端向服务器发送如下的9个请求头:
            Accep、tAccept-Language、 Content-Language 、DPR 、Downlink、 Save-Date、 Viewport-width 、width 、Content-Type、(值仅限于text/plain、 mulitport/form-data、 application/x-www-form-urlencoded三者之一)
        If the client sends an additional request header message to the server,则需要在服务器端,通过Access-Control-Allow-Headers对额外的请求头进行声明,否则这次请求会失败

例如:
res.setHeader('Access-Control-Allow-Headers','Content-Type','X-custom-Headers')

(3) CORS响应头部--Access-Control-Allow-Methods

  (3) CORS响应头部--Access-Control-Allow-Methods
        默认情况下,CORS仅支持客户端发起GET POST HEAD请求
        如果客户端希望通过PUT DELETE等方式请求服务器的资源,则需要在服务器端,通过Access-Control-Allow-Methods来指明实际请求所允许使用的HTTP方法.
        示例如下:
           

 //允许所有的HTTP请求方法:
    res.setHeader('Access-Control-Allow-Methods','*')
//只允许POST GET DELETE HEAD请求方法:
    res.setHeader('Access-Control-Allow-Methods','POST,GET,DELETE,HEAD')

(2.3)CORS请求的分类

  客户端在请求CORS请求时,根据请求方式和请求头的不同,可以将CORS的请求分为两大类:
        (1)简单请求
            (1)请求方式:GET POST HEAD三者之一
            (2)HTTP头部信息不超过以下几种字段:无自定义头部字段、Accept、 Accept-Language、 Content-Language 、DPR 、Downlink 、Save-Date 、Viewport-width、 width、 Content-Type、(只有三个值text/plain、 mulitport/form-data、 application/x-www-form-urlencoded)
        (2)预检请求
            (1)请求方式为GET POST HEAD之外的请求Method类型
            (2)请求头中包含自定义头部字段
            (3)向服务器发送了application/json格式的数据
        Before the browser formally communicates with the server,浏览器会先发送OPTION请求进行预测,以获知服务器是否允许该实际请求,所以这一次的OPTION请求称为"预检请求"
        服务器成功响应预检请求后,才会发送真正的请求,并且携带真实数据.

简单请求和预检请求的区别
    简单请求的特点:Only one request occurs between client and server
    预检请求的特点:There are two requests between client and server,OPTION预检请求成功之后,才会发起真正的请求.

3.JSONP

(3.1)JSONPconcept and characteristics

JSONP接口
    JSONP概念:浏览器通过<script>标签的src属性,请求服务器上的数据,同时,服务器返回一个函数的调用,这种请求数据的方式叫做JSONP

特点:
        JSONP不属于真正的Ajax请求,因为它没有XMLHttpRequest这个对象
        JSONP仅支持GET请求,不支持POST PUT DELETE等请求.


    创建JSONP接口的注意事项
        If it has been configured in the projectCORS跨域资源共享,为了防止冲突,必须配置CORS中间件之前声明JSONP接口,否则JSONPThe interface will be processed as CORS的接口.
       

 例如:  
                //优先创建JSONP接口
            app.get('/api/jsonp',(req,res)=>{})
                //在配置CORS中间件
            app.use(cors())
                //This is an openCORSS接口
            app.get('/api/get',(req,res)=>{})

(3.2) 实现JSONP接口的步骤

(3.2) 实现JSONP接口的步骤
        (1)获取客户端发送过来的回调函数的名字
        (2)得到要通过JSONP形式发送给客户端的数据
        (3)根据前两步得到的数据,拼接出一个函数调用的字符串
        (4)Concatenate the string obtained by asynchronous splicing,响应给客户端的<script>标签进行解析执行.

    具体代码示例:
     

  app.get('/api/jsonp',(req,res)=>{
                //1.Get the name of the callback function sent by the customer group
            const funcName=req.query.callback

                //2.得到要通过JSONP形式发送给客户端的数据
            const data={name:'zs',age:22}

                //3.根据前两步得到的数据,拼接出一个函数调用的字符串
            const scriptStr=`${funcName}({JSON.stringify(data)})`

                //4.Concatenate the string obtained by asynchronous splicing,响应给客户端的<script>标签进行解析执行.
            res.send(scriptStr)
        })

在网页中使用jQuery发起JSONP请求
        调用$.ajax()函数,提供JSONP的配置选项,从而发起JSONP请求,示例代码如下:
     

  //为JSONP按钮绑定点击事件处理函数
        $("#btnJSONP").on('click',function(){
            $.ajax({
                method:'GET',
                URL:'http://127.0.0.1/api/jsonp',
                dataType:'jsonp',
                success:function(res){
                    console.log(res)
                }
            })
        })

(3.3)讲一讲你对JSONP的理解?

1.Used in front-end web pagesajaxThe URL to request the cross-origin server  会报跨域错误

    用script标签的srcproperty to request the URL of a cross-origin server No cross-domain error will be reported,但是 It will directly use the requested encodingv8engine to run

   

2. We can write one on the backendjsA string recognized by the engine is sent to the front end,This string is like this:

    ' fn({"name":"karen"}) '

前端可以用script标签的srcproperty to request this URL,After the request is complete v8will run the code directly 去调用fn函数,So we have to create this function in advance

   

3.Problem with the name of the function:  前端可以通过querystringSend the function name as a parameter to the backend

    After the backend is parsed spliced ​​directly into the data(比如那个fn)

4.Proxy

核心代码:
var router=require("./router.js")
var request=require("request")//Is a back-end network request tool

router.get("/home",function(req,res){
	request("http://www.baidu.com/index.html",function(agr1,arg2,arg3){
		res.end(arg3)
	})
	
	  
})

   钓鱼网站--违法

            前端请求后端

            The backend requests other web page data 然后修改了 发给用户

      

    大数据分析

            Back end pleaseajax网址数据  数据处理 发给用户   

     

     爬虫--灰色

             Backend please other static files and data  数据处理 发给用户

     

     Proxy 代理服务

             Backends are legitimate to request other backends(oAuth授权-token)  再发给前端 The front end is written as its own page

原网站

版权声明
本文为[love bubble tea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020306373178.html