封装promise和反向代理第三方解决跨域问题

封装promise和反向代理第三方解决跨域问题

代码如下:

源码:https://github.com/pinktuziling84/promise

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./js/jquery.js"></script>
</head>
<body>
    <button id="btn">发送请求</button>
    <script>
        function PromiseAJAX (obj = {}){
            return new Promise((resolve,reject)=>{
              $.ajax({
                url: obj.url,
                type: obj.type,
                data: obj.data,
                dataType:'json',
                success:function(res){
                    resolve(res)
                },
                error:function(err){
                    reject(err)
                }
              })
            })
        }
        /*------------------------------------------*/
        $("#btn").on("click",function(){
           // console.log(11111)
           PromiseAJAX({
               url:'/api/v1/proxy',
               type:"get",
               data:{
               
               },
                }
           )
           .then(res =>{
                console.log(res)
           })
        })
        /*-----------------------------------------*/
        fetch('/api/v1/proxy')
        .then(res =>{
            return res.json()
        }).then(res =>{
            console.log(res)
        })
    </script>
</body>
</html>

利用服务器和服务器进行请求,服务器和服务器不存在跨域问题

const express= require("express");
const app =express();
app.use(express.static("./index"))
let axios=require("axios")
app.get('/api/v1/proxy',(req,res)=>{
    //axios 只是一个请求的库  反向代理跟axios没有关系
    let menu=encodeURI("沙拉")
    console.log(menu)
    axios.get(`https://apis.juhe.cn/cook/query.php?menu=${menu}&key=fd075da6f7c344cbbb8948ce659312ff&dtype=json`)
    .then(result =>{
        res.send({msg:result.data})
    })
})
app.listen(2333,res=>{
    console.log('server running at http://127.0.0.1:2333')
})

猜你喜欢

转载自blog.csdn.net/weixin_43764814/article/details/86499440