【HAVENT原创】NodeJS 短网址开发(调用第三方接口)

最近想弄个短网址的示例站点,在网上搜集了一些代码,都需要数据库支持,所以只能自己写个简单的不需要数据库支持的(PS:那就只能借调第三方的接口了)。

index.js 启动文件

'use strict';

var express = require('express');
var bodyParser = require('body-parser');

/* HH: 增加路由配置 HEAD */
const indexRouter = require('./router');

var app = express();

app.use(express.static('build'));

/* HH: 增加路由配置 BODY */
app.use('/', indexRouter);

app.use(bodyParser.json());
app.listen(8000);

 

router/index.js 路由主文件

'use strict';

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

const request = require('request');
const logger = require('../logger');

// 扩展路径配置
const apiRouter = require('./api');

router.get('/', function (req, res) {
    res.send('hello, express');
});

router.use('/api', apiRouter);


router.get('/:path', function (req, res) {
    var url = 'http://suo.im/' + req.params.path;
    var options = {
        url :  url,
        timeout: 2000,
        followAllRedirects: true
    };
    request(options,
        function(err, res1, body) {
            if (err) logger.error(err);
            if (res1) logger.debug(res1.request.uri.href);
            //if (body) logger.debug(body);

            if (res1 && res1.request && res1.request.uri.href) {
                res.redirect(res1.request.uri.href);
            } else {
                res.send('非法请求路径: /' + req.params.path);
            }
        }
    );
});

module.exports = router;

 

router/api.js 路由 api 接口文件

'use strict';

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

const request = require('request');
const logger = require('../logger');


router.get('/shortUrl/:encodeUrl', function (req, res) {
    var url = req.params.encodeUrl;
    if (url) {
        url = decodeURIComponent(url);
    }
    logger.info(url);

    var url = 'http://suo.im/api.php?url=' + encodeURIComponent(url);
    var options = {
        url :  url,
        json : true
    };
    request(options,
        function(err, res1, body) {
            var domain = req.protocol + '://' + req.headers.host;
            if (err) logger.error(err);
            //if (body) logger.info(body);
            if (domain) logger.debug(domain);
            var shortUrl = body.replace('http://suo.im', domain);
            res.send({
                'shortUrl' : shortUrl
            });
        }
    );
});


router.get('/:path', function (req, res) {
    logger.info(req.params.path);
    res.send('非法请求路径: /api/' + req.params.path);
});

module.exports = router;

 

前端访问静态页面 index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>URL Shortener - MY00.COM</title>
  <link href='http://fonts.font.im/css?family=Raleway' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <link href="css/styles.css" rel="stylesheet">
</head>
<body>

  <div class="site-wrapper">

    <div class="site-wrapper-inner">

      <div class="main-container">

        <div class="inner cover">
          <span class="glyphicon glyphicon-link"></span>
          <h1>URL Shortener</h1>
          <h4>os1.cc</h4>

          <div class="row">

            <div class="col-lg-12">
              <div class="input-group input-group-lg">
                <input id="url-field" type="text" class="form-control" placeholder="Paste a link...">
                <span class="input-group-btn">
                  <button class="btn btn-shorten" type="button">SHORTEN</button>
                </span>
              </div>
            </div>

            <div class="col-lg-12">
              <div id="link"></div>
            </div>

          </div>

        </div>

      </div>

    </div>

  </div>


<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="js/common.js"></script>
<script type="text/javascript">
$(function () {
    $('.btn-shorten').click(function () {
        var url = $('#url-field').val();
        if (url) {
            url = '/api/shortUrl/' + encodeURIComponent(url);
            HH.common.ajaxGet(url, function (response) {
                console.log(response);
                if (response.shortUrl) {
                    $('#link').show();
                    $('#link').html(response.shortUrl);
                }
            });
        }
    });
});
</script>

</body>
</html>

 

前端 common.js 脚本文件

/**
 * 全局通用模块
 * @author HAVENT
 **/

var HH = HH || {};

HH.common = {

    ajaxGet: function (url, callback) {
        $.ajax({
            url: url,
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            success: function (response, textStatus, jqXHR) {
                //console.log(response);

                if (callback) callback(response);
            },
            fail: function (response, textStatus, jqXHR) {
                //console.log(response);

                if (callback) callback(response);
            },
            error: function (xhr, textStatus) {
                //console.log(xhr);

                if (callback) callback(xhr);
            }
        });
    },

    ajaxPost: function (url, params, callback) {
        $.ajax({
            url: url,
            type: 'POST',
            data: JSON.stringify(params),
            contentType: 'application/json',
            dataType: 'json',
            success: function (response, textStatus, jqXHR) {
                //console.log(response);

                if (callback) callback(response);
            },
            fail: function (response, textStatus, jqXHR) {
                //console.log(response);

                if (callback) callback(response);
            },
            error: function (xhr, textStatus) {
                //console.log(xhr);

                if (callback) callback(xhr);
            }
        });
    }

};

 

效果如下:

3396fc8915866f09c967b958f5dd001be62.jpg

转载于:https://my.oschina.net/u/943746/blog/1859652

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值