当前位置:   article > 正文

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

node调第三方接口原生实现

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

index.js 启动文件

  1. 'use strict';
  2. var express = require('express');
  3. var bodyParser = require('body-parser');
  4. /* HH: 增加路由配置 HEAD */
  5. const indexRouter = require('./router');
  6. var app = express();
  7. app.use(express.static('build'));
  8. /* HH: 增加路由配置 BODY */
  9. app.use('/', indexRouter);
  10. app.use(bodyParser.json());
  11. app.listen(8000);

 

router/index.js 路由主文件

  1. 'use strict';
  2. const express = require('express');
  3. const router = express.Router();
  4. const request = require('request');
  5. const logger = require('../logger');
  6. // 扩展路径配置
  7. const apiRouter = require('./api');
  8. router.get('/', function (req, res) {
  9. res.send('hello, express');
  10. });
  11. router.use('/api', apiRouter);
  12. router.get('/:path', function (req, res) {
  13. var url = 'http://suo.im/' + req.params.path;
  14. var options = {
  15. url : url,
  16. timeout: 2000,
  17. followAllRedirects: true
  18. };
  19. request(options,
  20. function(err, res1, body) {
  21. if (err) logger.error(err);
  22. if (res1) logger.debug(res1.request.uri.href);
  23. //if (body) logger.debug(body);
  24. if (res1 && res1.request && res1.request.uri.href) {
  25. res.redirect(res1.request.uri.href);
  26. } else {
  27. res.send('非法请求路径: /' + req.params.path);
  28. }
  29. }
  30. );
  31. });
  32. module.exports = router;

 

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

  1. 'use strict';
  2. const express = require('express');
  3. const router = express.Router();
  4. const request = require('request');
  5. const logger = require('../logger');
  6. router.get('/shortUrl/:encodeUrl', function (req, res) {
  7. var url = req.params.encodeUrl;
  8. if (url) {
  9. url = decodeURIComponent(url);
  10. }
  11. logger.info(url);
  12. var url = 'http://suo.im/api.php?url=' + encodeURIComponent(url);
  13. var options = {
  14. url : url,
  15. json : true
  16. };
  17. request(options,
  18. function(err, res1, body) {
  19. var domain = req.protocol + '://' + req.headers.host;
  20. if (err) logger.error(err);
  21. //if (body) logger.info(body);
  22. if (domain) logger.debug(domain);
  23. var shortUrl = body.replace('http://suo.im', domain);
  24. res.send({
  25. 'shortUrl' : shortUrl
  26. });
  27. }
  28. );
  29. });
  30. router.get('/:path', function (req, res) {
  31. logger.info(req.params.path);
  32. res.send('非法请求路径: /api/' + req.params.path);
  33. });
  34. module.exports = router;

 

前端访问静态页面 index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>URL Shortener - MY00.COM</title>
  8. <link href='http://fonts.font.im/css?family=Raleway' rel='stylesheet' type='text/css'>
  9. <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css">
  10. <link href="css/styles.css" rel="stylesheet">
  11. </head>
  12. <body>
  13. <div class="site-wrapper">
  14. <div class="site-wrapper-inner">
  15. <div class="main-container">
  16. <div class="inner cover">
  17. <span class="glyphicon glyphicon-link"></span>
  18. <h1>URL Shortener</h1>
  19. <h4>os1.cc</h4>
  20. <div class="row">
  21. <div class="col-lg-12">
  22. <div class="input-group input-group-lg">
  23. <input id="url-field" type="text" class="form-control" placeholder="Paste a link...">
  24. <span class="input-group-btn">
  25. <button class="btn btn-shorten" type="button">SHORTEN</button>
  26. </span>
  27. </div>
  28. </div>
  29. <div class="col-lg-12">
  30. <div id="link"></div>
  31. </div>
  32. </div>
  33. </div>
  34. </div>
  35. </div>
  36. </div>
  37. <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
  38. <script src="js/common.js"></script>
  39. <script type="text/javascript">
  40. $(function () {
  41. $('.btn-shorten').click(function () {
  42. var url = $('#url-field').val();
  43. if (url) {
  44. url = '/api/shortUrl/' + encodeURIComponent(url);
  45. HH.common.ajaxGet(url, function (response) {
  46. console.log(response);
  47. if (response.shortUrl) {
  48. $('#link').show();
  49. $('#link').html(response.shortUrl);
  50. }
  51. });
  52. }
  53. });
  54. });
  55. </script>
  56. </body>
  57. </html>

 

前端 common.js 脚本文件

  1. /**
  2. * 全局通用模块
  3. * @author HAVENT
  4. **/
  5. var HH = HH || {};
  6. HH.common = {
  7. ajaxGet: function (url, callback) {
  8. $.ajax({
  9. url: url,
  10. type: 'GET',
  11. contentType: 'application/json',
  12. dataType: 'json',
  13. success: function (response, textStatus, jqXHR) {
  14. //console.log(response);
  15. if (callback) callback(response);
  16. },
  17. fail: function (response, textStatus, jqXHR) {
  18. //console.log(response);
  19. if (callback) callback(response);
  20. },
  21. error: function (xhr, textStatus) {
  22. //console.log(xhr);
  23. if (callback) callback(xhr);
  24. }
  25. });
  26. },
  27. ajaxPost: function (url, params, callback) {
  28. $.ajax({
  29. url: url,
  30. type: 'POST',
  31. data: JSON.stringify(params),
  32. contentType: 'application/json',
  33. dataType: 'json',
  34. success: function (response, textStatus, jqXHR) {
  35. //console.log(response);
  36. if (callback) callback(response);
  37. },
  38. fail: function (response, textStatus, jqXHR) {
  39. //console.log(response);
  40. if (callback) callback(response);
  41. },
  42. error: function (xhr, textStatus) {
  43. //console.log(xhr);
  44. if (callback) callback(xhr);
  45. }
  46. });
  47. }
  48. };

 

效果如下:

3396fc8915866f09c967b958f5dd001be62.jpg

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/69036
推荐阅读
相关标签
  

闽ICP备14008679号