Nav apraksta
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

server.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // Created by Mingliang Chen on 17/8/1.
  3. // illuspas[a]gmail.com
  4. // Copyright (c) 2018 Nodemedia. All rights reserved.
  5. //
  6. const Fs = require('fs');
  7. const Http = require('http');
  8. const Express = require('express');
  9. const bodyParser = require("body-parser");
  10. const basicAuth = require('basic-auth-connect');
  11. const HTTP_PORT = 80;
  12. const Logger = require('../core/logger');
  13. const context = require('../core/ctx');
  14. const vagRoute = require('./routes/vag');
  15. class NodeHttpServer {
  16. constructor(config) {
  17. this.config = config;
  18. this.port = config.VAG.http.port = config.VAG.http.port ? config.VAG.http.port : HTTP_PORT;
  19. let app = Express();
  20. // 使用 body-parser 中间
  21. app.use(bodyParser.urlencoded({ extended: true }));
  22. app.use(bodyParser.json());
  23. if (this.config.VAG.auth && this.config.VAG.auth.api) {
  24. app.use('/api/*', basicAuth(this.config.VAG.auth.api_user, this.config.VAG.auth.api_pass));
  25. }
  26. // ntv 简化
  27. //app.use('/api/v1/vag', vagRoute(context));
  28. app.use('/api', vagRoute(context));
  29. app.get('/', (req, res, next) => {
  30. res.setHeader('Content-type', 'application/json');
  31. res.setHeader('Server', 'ntv-api-server on www.ruiboyun.com');
  32. res.send('{"success":true,"name":"api server","version":"1.1"}');
  33. res.end();
  34. });
  35. this.httpServer = Http.createServer(app);
  36. }
  37. run() {
  38. this.httpServer.listen(this.port, () => {
  39. Logger.log(`Http API Server started on port: ${this.port}`);
  40. });
  41. this.httpServer.on('error', (e) => {
  42. Logger.error(`Http API Server ${e}`);
  43. });
  44. this.httpServer.on('close', () => {
  45. Logger.log('Http API Server Close.');
  46. });
  47. }
  48. stop() {
  49. this.httpServer.close();
  50. if (this.httpsServer) {
  51. this.httpsServer.close();
  52. }
  53. }
  54. }
  55. module.exports = NodeHttpServer