Typescript Express节点-POST请求不起作用

时间:2018-12-05 13:04:21

标签: node.js typescript express

使用GitHub webhooks,我正在将一个旧项目转换为TypeScript,却迷失了方向。

当我将json数据发布到localhost/github时,我应该看到111 222 hi打印在日志上。但是我只看到111。看来我的Typescript项目不了解req.on('data') req.on('end'),但我不确定为什么。

我已经设置了身体解析器以转换为json,但是没有运气。我在这里想念什么?

app.ts

import * as express from "express";
import * as bodyParser from "body-parser";
import { Routes } from "./routes/routes";
import * as mongoose from "mongoose";
import * as schedule from 'node-schedule';

import { StatusController } from './controllers/status.controller';

class App {

  public status: StatusController = new StatusController()
  public app: express.Application;
  public routePrv: Routes = new Routes();
  public _db: string = 'madeupname';
  public _mongo: string = 'mongodb://localhost:27017';

  constructor() {
    this.app = express();
    this.config();
    this.mongoSetup();
    this.routePrv.routes(this.app);
  }

  private config(): void {
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({
      extended: false
    }));
  }

  private mongoSetup(): void {
    mongoose.Promise = global.Promise;
    mongoose.connect(`${this._mongo}/${this._db}`, {
      useNewUrlParser: true
    });
  }

}

export default new App().app;

status.controller.ts

import { StatusSchema } from '../models/status.model';
import { Request, Response } from 'express';

import * as crypto from 'crypto';
import * as moment from 'moment';
import * as fs from 'fs';
import * as request from 'request';
import * as Slack from 'slack-node';
import { Helpers } from '../helpers';

import { GitHubConfig } from '../../config/github';

const secret = GitHubConfig.secret;

export class GhNewPrController {

  public helpers: Helpers = new Helpers();
  public ghNewPrMethod: GhNewPrMethod = new GhNewPrMethod();

  public post(req: Request, res: Response) {
    let jsonString = '';
    console.log(111)

    req.on('data', (data) => {
      console.log(22);
      jsonString += data;
    })
    .on('end', () => {
      console.log('hi');
      const hash = `sha1=${crypto.createHmac('sha1', secret).update(jsonString).digest('hex')}`;
      console.log(jsonString);
      const payload = JSON.parse(jsonString);

      if (hash !== req.headers['x-hub-signature']) {
        const data = JSON.stringify({
          'error': 'invalid key',
          key: hash
        });
        return res.status(401).send(data);
      }
    });
  }
}

0 个答案:

没有答案