• 前端jsonp


    ##jsonp
    一、创建jsonp接口注意事项:
    如果项目中已经配置了CORS跨域资源共享,为了防止冲突,必须在配置CORS中间件之前声明jsonp接口,否则jsonp接口会被处理成开启了CORS的接口。

    二、实现步骤:
    1. 获取客户端发送过来的回调函数的名字
    2. 得到要通过jsonp形式发送给客户端的数据
    3. 根据前两步得到的数据,拼接出一个函数调用的字符串
    4. 把上一步拼接得到的字符串,响应给客户端的`<script>`标签进行解析执行

    三、调用jsonp接口
    使用$.ajax()函数,提供jsonp的配置选项,从而发起jsonp请求

    jsonp.html如下

     1 <!DOCTYPE html>
     2 <html>
     3     <head>
     4         <meta charset="utf-8">
     5         <title>jsonp</title>
     6     </head>
     7     <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
     8     <body>
     9         <button id="jsonp">jsonp</button>
    10         <script type="text/javascript">
    11             $($('#jsonp').on('click', function(){
    12                 $.ajax({
    13                     type: 'GET',
    14                     url: 'http://127.0.0.1/jsonp',
    15                     dataType: 'jsonp',
    16                     success:function(res){
    17                         console.log(res)
    18                     }
    19                 })
    20             }))
    21         </script>
    22     </body>
    23 </html>

    后端使用nodejs index.js如下

     1 const express = require('express');
     2 const app = express();
     3 const cors = require('cors');
     4 //注意需要定义子啊cors之间 jsonp只支持get请求
     5 app.get('/jsonp', (req, res) => {
     6     console.log('/jsonp');
     7     //获取克服的发送过来的回调函数的名字
     8     const funcName = req.query.callback;
     9     //得到要通过jsonp形式发送给客户端的数据
    10     const data = {name: 'jsonp'};
    11     //根据前两步得到的数据,凭借出一个函数调用的字符串
    12     const scriptStr = `${funcName}(${JSON.stringify(data)})`;
    13     //把拼接的字符串响应给客户端的`<script>`标签进行解析
    14     res.send(scriptStr);
    15 });
    16 app.use(cors());
    17 app.listen(80, () => {
    18     console.log('server running at 127.0.0.1')
    19 })

    测试结果如下:

  • 相关阅读:
    几种常用的曲线
    0188. Best Time to Buy and Sell Stock IV (H)
    0074. Search a 2D Matrix (M)
    0189. Rotate Array (E)
    0148. Sort List (M)
    0859. Buddy Strings (E)
    0316. Remove Duplicate Letters (M)
    0452. Minimum Number of Arrows to Burst Balloons (M)
    0449. Serialize and Deserialize BST (M)
    0704. Binary Search (E)
  • 原文地址:https://www.cnblogs.com/qkq505/p/16031046.html
Copyright © 2020-2023  润新知