node服务器转发请求以及node拦截ajax请求

如何实现服务器转发请求第三方接口的数据,也是node服务器解决跨域的问题
通过localhost转发接口

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

的数据,代码实例如下:
html

<!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();
    }
})

启动服务之后,就可以通过:

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

来访问数据。

二,下面来探讨一下node服务器如何拦截ajax请求,注意,页面引入jquery引入第三方是不存在跨域的问题,只有通过ajax调用第三方接口请求数据的时候,才会存在跨域。

我们将html定义如下

<!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读取静态的资源文件

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

在页面上定义2个按钮

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

利用jquery请求按钮点击事件触发

$('.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'
        },error:function() {
            console.log('失败');
        }
    })
})

在node主入口js文件里面进行拦截请求

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


//服务器拦截post请求
server.post('/api/user/login',data:{'postdata':'fdsafd','dsf':'343'}
    })
})

点击get按钮,前端请求的数据如下:

点击post按钮,前端请求的数据如下:

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...