nodejs跨域请求

js中,想实现跨域请求,在各种尝试之后,最终选择了用nodejs发送跨域请求,还是可以的,下面记录一下过程。
我要访问的 url 是域名+端口形式的域名。

1.首先安装nodejs,我这里安装了全局的,安装过程自己百度一下,网上很多

2.这个demo的目录是E盘的根目录下创建了 server.js E盘的根目录下创建一个zx目录,zx目录下面创建index.html ,我这里创建了js目录 css目录(E:/zx/js 里面放js脚本),当然可以创建css,js,image,根据你的需要

3.这一步骤,是第2步中的代码示例

server.js

var express = require('C:/Users/user/AppData/Roaming/npm/node_modules/express');
//如果你安装的全局的express可以require出来不报错,可以直接 var express = require('express');我这里是require报错,找不到,就引入了全路径
var app = express();
var bodyParser = require('C:/Users/user/AppData/Roaming/npm/node_modules/body-parser');
var tools = require('./zx/js/tools');
//这个tools是同事那里借来的,不知道同事是不是网上找的工具类,如果冒犯,请见谅

// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false });


 //加载zx目录下面的静态资源
app.use(express.static('zx'));

 //加载index.html入口界面  __dirname是nodejs中的全局变量
app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

//接收zx/index.html脚本中的请求 /unifyService 匹配这个url,接收此url过来的请求,然后转发出去
app.post('/unifyService', urlencodedParser, function (req, res) {

    //获取请求参数
    var args = tools.getArgs(req);

    //这个是转发出去的url,跨域的,可以替换成你们自己的,我这个错的,不通,随便写的
    var remoteUrl = "https://testpos.ebankunion.com/unifyService";

 //调用工具类的post方法发送请求,代码示例在下面
 tools.http_client_post(remoteUrl, args,function (error, response, body) {
        if (!error && response.statusCode == 200) {
           //如果请求成功,把请求结果转成json格式,给到请求这个server.js的脚本
            res.json(body);
        }
    });

})

 //启动本地的8081端口,
 //可以启动nodejs 命令:node server.js
 //浏览器访问  http://127.0.0.1:8081/index.html  
var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("应用实例,访问地址为 http://%s:%s", host, port)

})

./zx/js/tools
tools.js

var request = require('C:/Users/user/AppData/Roaming/npm/node_modules/cnpm/node_modules/request');
var querystring = require('C:/Users/user/AppData/Roaming/npm/node_modules/cnpm/node_modules/querystring');

module.exports = tools = {
    /**
     *@description 获取http请求参数
     */
    getArgs:function(req){
        if (typeof req.query === "object" && !(req.query instanceof Array)){  
            console.log('get request args');
            var hasProp = false;  
            for (var prop in req.query){  
                hasProp = true;  
                break;  
            }  
            if (hasProp){  
                return req.query;//get方法参数  
            }
        }
        return req.body;//post方法参数  
    },

    /**
     *@description http get请求
     */
    http_client_get:function(url, data,callback, timeout ){
        if(!timeout){
            timeout = 30;
        }
        url = url+'?'+querystring.stringify(data);
        request(url, timeout , callback);
    },

    /**
     *@description http post请求
     */
    http_client_post:function(url,data,callback,timeout){
        if(!timeout){
            timeout = 30;
        }
        request.post(url, {form:data}, callback);
    },
 };

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

    <title>获取二维码</title>

   <link rel="stylesheet" href="css/dialog.css" />
   <script type="text/javascript" src="js/jquery-3.2.1.min.js" ></script>
   <script type="text/javascript" src="js/dialog.js" ></script>

   <style type="text/css">
        *{padding: 0  0;margin: 0 auto;}
        .div_out{
            min-width:300px; max-width:638px;
            margin:0 auto;position:relative;
        }
        .div_title{
            width: 100%;
            height: 50px;
            background-color: cornflowerblue;
        }
        .title_text{
            text-align: center;
            line-height: 50px;
            color: white;
            font-size: 1.2rem;
        }
        .div_body{
            width: 90%;
            height: auto;
            margin-top: 30px;
            margin-left: 5%;
            margin-right: 5%;
            font-size: 1.1rem;
        }
        .div_item{
            width: 100%;
            height: 50px;
            margin-top: 10px;
            //background-color: chartreuse;
        }

        .div_item_left{
            width: 35%;
            height: 50px;
            float: left;
            //background-color: azure;
        }

        .div_item_right{
            width: 65%;
            height: 50px;   
            float: left;
            //background-color: beige;
        }

        .text_input{
            height: 30px;
            display: block;
            border: 1.5px solid #6495ED;
            border-radius: 5px;
            margin-top: 10px;
            padding-left: 5px;
        }
        .text_span{
            width: 100%;
            height: 50px;
            display: block;
            line-height: 50px;

        }
        .div_submit{
            width: 100%;
            height: auto;
            margin-top: 20px;
            //background-color: chartreuse;
        }

        .submit_button{
            width: 30%;
            height: 40px;
            display: block;
            font-size: 1.1rem;
            color: white;
            background-color: cornflowerblue;
            border: none;
            border-radius: 5px;
            margin-top: 10px;

        }

        .div_img{
            height: auto;
            margin-top: 20px;
            text-align: center;         
        }

        #img_qrcode {
            width: 300px;
            height: 300px;
        }
    </style>

</head>
<body>
<div class="div_out">
        <div class="div_title">
            <p class="title_text">获取二维码</p>
        </div>
        <div class="div_body">
            <div class="div_item">
                <div class="div_item_left">
                    <span class="text_span">mcssn:</span>
                </div>
                <div class="div_item_right">
                    <input class="text_input" id="mcssn_text" type="text" />
                </div>
            </div>

            <div class="div_item">
                <div class="div_item_left">
                    <span class="text_span">expire(seconds):</span>
                </div>
                <div class="div_item_right">
                    <input class="text_input" id="time_seconds" type="text" value="2592000"/>
                </div>
            </div>  

            <div class="div_submit">
                <input class="submit_button" type="button" value="提交" onclick="request_qrcode()"/>
            </div>
        </div>  

        <div class="div_img">
            <img id="img_qrcode" src="" />
        </div>

    </div>

</body>
<script>
function request_qrcode(){
     var mcssn = $("#mcssn_text").val();
     var time = $("#time_seconds").val();
     if("" == mcssn || undefined == mcssn || null == mcssn) {
        showDialog("主控流水号不能为空");
        return;
     }
     if("" == time || undefined == time || null == time) {
        showDialog("有效时间不能为空");
        return;
     }
    //这里把请求发送到server.js 跨域请求由server.js转发出去
     var qrcode_url = "http://127.0.0.1:8081/unifyService";
     var req_data = "service=service.getqrcode&mcssn="+mcssn+"&action_name=QR_SCENE&expire_seconds="+time;
    $.ajax({
            url: qrcode_url,
            data: req_data,
            timeout: 5000,//这里必须设置超时,否则报错 net::ERR_CONNECTION_REFUSED 这个可自行百度
            type: 'POST',
            datatype: 'json',
            success: function(data) {
                var res = eval("(" + data + ")");               
                if(res.retcode == "0000") {
                    var qrcode_img_url = res.qrcode_img
                    $("#img_qrcode").attr('src',qrcode_img_url);

                } else {

                    showDialog("请求成功,返回错误");
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                showDialog("请求出错了");
            }
        });



}
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值