node服務器轉發請求以及node攔截ajax請求

如何實現服務器轉發請求第三方接口的數據,也是node服務器解決跨域的問題
經過localhost轉發接口javascript

https://m.maizuo.com/v4/api/film/now-playing?__t=1523003169298&page=1&count=5

的數據,代碼實例以下:
htmlcss

<!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">
    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <title>cross</title>
</head>
<body>
    
</body>
<script>
    $.ajax({
        url:'/v4/api/film/now-playing?__t=1523003169298&page=1&count=5',
        type:'GET',
        success:function(res) {
           console.log('success');
        },
        error:function() {
            console.log('error');
        }
    })
</script>
</html>
// 跨域問題,當你沒法操做後臺是否能夠跨域的時候
var http = require('http');
var https = require('https');
var server = http.createServer();
var fs = require('fs');
server.listen('8080');
var url = require('url');

server.on('request',(request,response)=>{
    var path = url.parse(request.url);
    if(path.pathname == '/') {
        fs.readFile('./html/coress.html',(err,info)=>{
            response.write(info);
            response.end();
        })
    } else if(path.pathname.startsWith('/v4')) { //服務器轉發請求
     //建立請求
      var request =  https.request({
            hostname:'m.maizuo.com',
            port:'443',
            path:path.path,
            method:'GET'
        },(resp)=>{
            let results = '';
            //監聽接受數據
            resp.on('data',(dataObj)=>{
                results += dataObj;
            })
         //監聽關閉
            resp.on('end',()=>{
                response.write(results);
                response.end();
            })
        })
        // 發送請求
        request.end();
    }
})

啓動服務以後,就能夠經過:html

http://localhost:8080/v4/api/film/now-playing?__t=1523003169298&page=1&count=5

來訪問數據。前端

二,下面來探討一下node服務器如何攔截ajax請求,注意,頁面引入jquery引入第三方是不存在跨域的問題,只有經過ajax調用第三方接口請求數據的時候,纔會存在跨域。java

咱們將html定義以下node

<!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">
    <!-- 經過express的static插件讀取靜態文件-->
    <link rel="stylesheet" type="text/css" href="./static/style.css" />
    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <div>這是一個div </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <div>這是一個div  </div>
    <input type="button" value="get按鈕" class="btn1"/>
    <input type="button" value="post按鈕" class="btn2"/>
     <!-- 經過express的static插件讀取靜態文件-->
    <script type="text/javascript" src="./static/test.js"></script>
 </body>
</html>

咱們將css文件和js文件一致放到public文件夾下面
咱們經過express提供的第三方插件static讀取靜態的資源文件jquery

server.use('/static',express.static(__dirname+'/public'));

在頁面上定義2個按鈕ajax

<input type="button" value="get按鈕" class="btn1"/>
    <input type="button" value="post按鈕" class="btn2"/>

利用jquery請求按鈕點擊事件觸發express

$('.btn1').on('click',function() {
    $.ajax({
        url:'/api/user/login?name=zs&password=lisi',
        method:'GET',
        success:function(data) {
           console.log('成功');
           console.log(data);
        },
        error:function() {
            console.log('失敗');
        }
    })
})

$('.btn2').on('click',function() {
    $.ajax({
        url:'/api/user/login',
        method:'POST',
        data:{
            name:'sz',
            password:'r4tr4'
        },
        success:function(data) {
           console.log('成功');
           console.log(data);
        },
        error:function() {
            console.log('失敗');
        }
    })
})

在node主入口js文件裏面進行攔截請求json

server.get('/',(req,res)=>{
    fs.readFile('./html/node.html',(err,info)=>{
        if(!err) {
            res.write(info);
            res.end();
        }
    })
})
//服務器攔截get請求
server.get('/api/user/login',(req,res)=>{
    console.log(req.url);
    res.json({
        status:200,
        message:'登陸成功',
        data:{'getData':'fdsafds','goods':'ddd','dsf':'343'}
    })
})


//服務器攔截post請求
server.post('/api/user/login',(req,res)=>{
    console.log(req.url);
    res.json({
        status:200,
        message:'登陸成功',
        data:{'postdata':'fdsafd','goods':'ddd','dsf':'343'}
    })
})

點擊get按鈕,前端請求的數據以下:
圖片描述

點擊post按鈕,前端請求的數據以下:
圖片描述

相關文章
相關標籤/搜索