编写JSONP接口

JSONP的概念与特点

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

特点

  1. JSONP不属于真正的Ajax请求,因为它没有使用XMLHttpRequest这个对象。
  2. JSONP仅支持GET请求,不支持POST、PUT、DELETE等请求。

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

代码编写:
22.测试接口跨域问题.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <button id="btnGet" >get</button>
    <button id="btnPost">post</button>
    <button id="btnJsonp" >btnJSONP</button>
    <script>
        $(function(){
            //测试get接口
            $('#btnGet').on('click',function(){
                $.ajax({
                    type:'GET',
                    url:'http://127.0.0.1:8080/api/get',
                    data:{name:'zs',age:20},
                    success:function(res){
                        console.log(res);
                    }
                })
            })
            //测试post接口
            $('#btnPost').on('click',function(){
                $.ajax({
                    type:'POST',
                    url:'http://127.0.0.1:8080/api/post',
                    data:{name:'栓剂解决',author:"老久"},
                    success:function(res){
                        console.log(res);
                    }
                })
            })
               //测试JSONP接口
               $('#btnJsonp').on('click',function(){
                $.ajax({
                    type:'GET',
                    url:'http://127.0.0.1:8080/api/jsonp',
                    dataType:'jsonp',
                    success:function(res){
                        console.log(res);
                    }
                })
            })
        })

    </script>
</body>
</html>

20.使用express写接口.js

const express = require('express')

//创建服务器实例
const app = express()
//配置解析表单数据的中间件
app.use(express.urlencoded({extended: false}))

//必须在配置cors中间件之前,配置JSONP的接口【这个接口不会被处理成CORS接口】
app.get('/api/jsonp',(req, res)=>{
    //TODO:定义jsonp接口具体实现过程

    //1、获取客户端发送过来的回调函数的名字
   const funcName = req.query.callback
    //2、得到要通过JSONP形式发送给客户端的数据
    const data = {name:'zz',age:12}
    //3、拼接一个函数调用的字符串
    const scriptStr = `${funcName}(${JSON.stringify(data)})`
    //4、把上一步拼接得到的字符串,响应给客户端<script>标签进行解析执行
    res.send(scriptStr)

})

//一定要在路由之前配置cors中间件,从而解决接口跨域问题【后续使用接口,都会被处理成CORS接口】
const cors = require('cors')
app.use(cors())

const router = require('./21.apiRouter')
//把路由模块 注册到app上
app.use('/api',router)

//启动服务器
app.listen(8080,()=>{
    console.log("serve is running...")
})

//启动:nodemon .\20.使用express写接口

21.apiRouter.js

const express = require('express')
const router = express.Router()

router.get('/get',(req,res)=>{
    //通过req.query获取客户端通过查询字符串,发送带服务器的数据
    const query = req.query
    //调用res.send()方法 向客户端响应处理的结果
    res.send({
        status: 0,//0成功 1失败
        meg:'get请求成功',
        data: query
    })
})

router.post('/post',(req,res)=>{
    //通过req.query获取客户端通过查询字符串,发送带服务器的数据
    const query = req.query
    //调用res.send()方法 向客户端响应处理的结果
    res.send({
        status: 0,//0成功 1失败
        meg:'post请求成功',
        data: query
    })
})
//在这里挂载路由
module.exports = router

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值