• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript body-parser.raw函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中body-parser.raw函数的典型用法代码示例。如果您正苦于以下问题:TypeScript raw函数的具体用法?TypeScript raw怎么用?TypeScript raw使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了raw函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: return

  return (req, res, next) => {
    // header names are lower-cased
    // https://nodejs.org/api/http.html#http_message_headers
    const signature = req.headers["x-line-signature"];

    if (!signature) {
      next();
      return;
    }

    const validate = (body: string | Buffer) => {
      if (!validateSignature(body, secret, signature)) {
        next(new SignatureValidationFailed("signature validation failed", signature));
        return;
      }

      const strBody = Buffer.isBuffer(body) ? body.toString() : body;

      try {
        req.body = JSON.parse(strBody);
        next();
      } catch (err) {
        next(new JSONParseError(err.message, strBody));
      }
    };

    if (typeof req.body === "string" || Buffer.isBuffer(req.body)) {
      return validate(req.body);
    }

    // if body is not parsed yet, parse it to a buffer
    raw({ type: "*/*" })(req as any, res as any, () => validate(req.body));
  };
开发者ID:eggyo,项目名称:dang-ai,代码行数:33,代码来源:middleware.ts


示例2:

 app.use((req: express.Request, res, next) => {
   if (req.path === "/post/binary") {
     bodyParser.raw({ type: "*/*" })(req, res, next);
   } else {
     bodyParser.json({ type: "application/json" })(req, res, next);
   }
 });
开发者ID:nkjm,项目名称:line-bot-sdk-nodejs,代码行数:7,代码来源:test-server.ts


示例3: if

 app.use((req: express.Request, res, next) => {
   if (req.path === "/mid-text") {
     bodyParser.text({ type: "*/*" })(req, res, next);
   } else if (req.path === "/mid-buffer") {
     bodyParser.raw({ type: "*/*" })(req, res, next);
   } else if (req.path === "/mid-json") {
     bodyParser.json({ type: "*/*" })(req, res, next);
   } else {
     next();
   }
 });
开发者ID:nkjm,项目名称:line-bot-sdk-nodejs,代码行数:11,代码来源:test-server.ts


示例4: serve

  async serve(port, websockets: boolean = false): Promise<Object> {
    var http = require("http");

    var express = require("express");
    var cookieParser = require("cookie-parser");
    var bodyParser = require("body-parser");
    var multer = require("multer"); // v1.0.5
    var upload = multer(); // for parsing multipart/form-data

    var requestLimit = this.getGlobalParams().requestLimit
      ? this.getGlobalParams().requestLimit
      : "20mb";
    var app = express();
    app.use(cookieParser());
    app.use(
      bodyParser.text({
        type: "text/plain"
      })
    );
    app.use(
      bodyParser.json({
        limit: requestLimit
      })
    );
    app.use(
      bodyParser.urlencoded({
        extended: true
      })
    );
    app.use(upload.array("file"));
    // Will lower the limit soon, we should have a library that handle multipart file
    app.use(
      bodyParser.raw({
        type: "*/*",
        limit: requestLimit
      })
    );

    app.set("trust proxy", "loopback, 10.0.0.0/8");

    app.use(this.handleRequest.bind(this));
    this.serveStaticWebsite(express, app);

    this._http = http.createServer(app).listen(port);
    if (websockets) {
      // Activate websocket
      this.output("Activating socket.io");
      this._io = require("socket.io")(this._http);
      this.emit("Webda.Init.SocketIO", this._io);
    }
    this.serveIndex(express, app);
    this.output("Server running at http://0.0.0.0:" + port);
    return new Promise(() => {});
  }
开发者ID:loopingz,项目名称:webda-shell,代码行数:54,代码来源:http.ts


示例5: constructor

    constructor(options) {

        super();

        // In case of no options
        !options && (options = {});

        // Load default configuration
        this.config = require('../defaultServerConfig.js');

        // Set initial status
        this.status = -1;

        // Overwrite defaults
        for (let option in options)
            this.config[option] = options[option];

        // Create the express app
        this.server = express();

        // Use compression on all requests
        // @todo toggle compression with optional parameter
        //this.server.use(compression({threshold:0}));

        // Create router
        this.router = express.Router();

        // Set upload limit
        this.server.use(bodyParser.raw({
            limit: this.config.uploadLimit
        }));

        // Block libwww-perl
        this.server.use(
            (req, res, next) =>
                /libwww-perl/.test(req.get('user-agent')) ? res.status(403).end() : next());

        // Parse json api requests
        this.server.use(bodyParser.urlencoded({ extended: true }));
        this.server.use(bodyParser.json());


        // Add headers
        this.server.use((req, res, next) => {

            if (this.config.serverHeader)
                res.setHeader(
                    'Server',
                    'ZenX/' + packageInfo.version);

            res.setHeader('Connection', 'Keep-Alive');
            res.setHeader('Keep-Alive', 'timeout=15, max=100');

            return next();

        });

        // Standard middleware
        this.server.use(helmet.xssFilter());
        this.server.use(cookieParser());
        this.server.use(multipart());
        this.server.use(methodOverride());

        // Disable x-powered-by header
        this.server.disable('x-powered-by');

        // A route to be used later
        this.server.use(this.router);

        // If a static content path was provided
        if (this.config.static) {

            // Always add cache control header
            this.server.use(function(req, res, next) {

                res.setHeader("Cache-Control", "max-age=31104000, public");
                res.setHeader('Expires',
                    new Date(Date.now() + 345600000).toUTCString());

                return next();

            });

            // Serve static content
            this.server.use(
                express.static(
                    path.resolve(this.config.static)));

        }

        // Not found
        this.server.get('*', function(req, res) {

            res.writeHead(404, 'Not found');

            res.end('404: Not found');

        });

        var config = this.config;
//.........这里部分代码省略.........
开发者ID:raelgor,项目名称:zen-arena,代码行数:101,代码来源:Server.ts


示例6: require

import * as http from 'http';
import express = require('express');
import {
    json,
    raw,
    text,
    urlencoded,
} from 'body-parser';

const app = express();

app.use(json());
app.use(raw());
app.use(text());
app.use(urlencoded());

const jsonParser = app.use(json({
    inflate: true,
    limit: '100kb',
    type: 'application/*',
    verify: (
        req: http.IncomingMessage,
        res: http.ServerResponse,
        buf: Buffer,
        encoding: string
    ) => {
        return true;
    }
}));
app.use(jsonParser);
开发者ID:AlexGalays,项目名称:DefinitelyTyped,代码行数:30,代码来源:body-parser-tests.ts


示例7: require

'use strict';

import * as fs from 'fs';
import * as express from 'express';
import * as request from 'request';
import * as bodyParser from 'body-parser';
import pump = require('pump');

// windows 7 sp1 64-bit
// node 6.0 not working
// node 0.10.31 works

const app = express();
app.use(bodyParser.raw());


app.post('/foo', function (req, res) {
  console.log('****** post on /foo: ', req.body);

  const output_filename = './output____video.mp4';
  const output = fs.createWriteStream(output_filename);
  pump(
    req,
    output,
    (err) => {
      console.log('****** end on pump receive: ', err);
      return res.status(200).json('OK');
    }
  );
});
开发者ID:nkint,项目名称:post-stream,代码行数:30,代码来源:index.ts


示例8: express

import { createUserRouter } from './routes/userRouter';
import { createPhotoRouter } from './routes/photoRouter';
import { createCommentRouter } from './routes/commentRoute';
import { createGetUser } from './middleware/getUser';
import { Utils } from './utils/utils';
import { WebSocketService } from './services/WebSocketService';
import { AsyncProcessor } from './services/AsyncProcessor';
import { FileService } from './services/FileService';
import { DataBus } from './services/DataBus';

const app = express();
app.use(logger('tiny'));
app.disable('x-powered-by');
app.set('port', config.port);
app.use(bodyParser.json());
app.use(bodyParser.raw({type: 'application/x-binary', limit : '2mb'}))
app.use(cookieParser());

const server = http.createServer(app);
const cryptoService = new CryptoService();
const utils = new Utils(cryptoService);
const dbService = new DbService(config, utils);
const fileService = new FileService(config, fs, path, pump);
const getUser = createGetUser(dbService, utils);
const dataBus = new DataBus();
const asyncProcessor = new AsyncProcessor(dbService, dataBus);
const webSocketService = new WebSocketService(
    getUser,
    app,
    asyncProcessor,
    server,
开发者ID:ravendyg,项目名称:photo-tl-server,代码行数:31,代码来源:index.ts


示例9: express

import express from 'express';
import cors from 'cors';
import { LogMiddleware, CacheMiddleware, CacheTimes, RateLimiter } from './middleware';
import { Web3Proxy } from "./web3";
import { Config } from "../services/config";

const app = express();
const bodyParser = require('body-parser');
app.use(
  bodyParser.json({
    limit: 100000000
  })
);
app.use(
  bodyParser.raw({
    limit: 100000000
  })
);
const chains = Config.chains()
const networks: any = {};
for (let chain of chains) {
  for (let network of Object.keys(config.chains[chain])) {
    networks[chain] = networks[chain] || {};
    Object.assign(networks[chain], {
      [network]: true
    });
  }
}

function bootstrap(path?: string) {
  const fs = require('fs');
开发者ID:bitpay,项目名称:bitcore,代码行数:31,代码来源:index.ts


示例10: Promise

 getBody = new Promise(resolve => {
   raw({ type: "*/*" })(req as any, res as any, () => resolve(req.body));
 });
开发者ID:SaKu2110,项目名称:Alexa_LINE_Bot,代码行数:3,代码来源:middleware.ts


示例11: async

        log.error(err)
        // Continue
    }

    return { success: true }
})

api.post('/datasets/:datasetId/setTags', async (req: Request, res: Response) => {
    const datasetId = expectInt(req.params.datasetId)

    await Dataset.setTags(datasetId, req.body.tagIds)

    return { success: true }
})

api.router.put('/datasets/:datasetId/uploadZip', bodyParser.raw({ type: "application/zip", limit: "50mb" }), async (req: Request, res: Response) => {
    const datasetId = expectInt(req.params.datasetId)

    await db.transaction(async t => {
        await t.execute(`DELETE FROM dataset_files WHERE datasetId=?`, [datasetId])
        await t.execute(`INSERT INTO dataset_files (datasetId, filename, file) VALUES (?, ?, ?)`, [datasetId, 'additional-material.zip', req.body])
    })

    res.send({ success: true })
})

api.delete('/datasets/:datasetId', async (req: Request, res: Response) => {
    const datasetId = expectInt(req.params.datasetId)

    const dataset = await Dataset.findOne({ id: datasetId })
    if (!dataset)
开发者ID:OurWorldInData,项目名称:owid-grapher,代码行数:31,代码来源:api.ts


示例12: require

let path = require('path');
let bodyParser = require('body-parser');
let cookieParser = require('cookie-parser');
let CONFIG = require('../../config');
const SSR = (process.env.SSR === 'true' || !!~process.argv.indexOf('--ssr') || CONFIG.SSR)

const requiredMiddleware : any = [
  bodyParser.raw({limit:CONFIG.maxFileSize || '50mb'}),
  bodyParser.json(),
];


const middleware : any = [
  {
    title:'isomorphic-middleware' ,
     enabled:SSR ,
     name:'iso' ,
     deps(){
       require('babel-register')(CONFIG.webpack.loaders.babel);

     }
   }

]
export {requiredMiddleware, middleware}

开发者ID:Echo-Peak,项目名称:starter-kits,代码行数:25,代码来源:index.ts


示例13: require

import express = require('express');
import {Request, Response} from 'express';
import {raw, json, text, urlencoded, ParsedAsJson, ParsedAsText, ParsedRaw, ParsedAsUrlencoded} from 'body-parser';

const app = express();

app.post('/rawdemo', raw(), (req: Request & ParsedRaw, res: Response) => {
    console.log(req.body.readUInt8(0));
});

app.post('/jsondemo', json(), (req: Request & ParsedAsJson, res: Response) => {
    console.log(req.body.whatever);
});

app.post('/textdemo', text(), (req: Request & ParsedAsText, res: Response) => {
    console.log(req.body.substr(3));
});

app.post('/urlencodeddemo', urlencoded(), (req: Request & ParsedAsUrlencoded, res: Response) => {
    console.log(req.body.whatever);
});
开发者ID:felixfbecker,项目名称:typed-body-parser,代码行数:21,代码来源:express.ts



注:本文中的body-parser.raw函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript body-parser.text函数代码示例发布时间:2022-05-25
下一篇:
TypeScript body-parser.json函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap