本文整理汇总了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));
};
示例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);
}
});
示例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();
}
});
示例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(() => {});
}
示例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;
//.........这里部分代码省略.........
示例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);
示例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');
}
);
});
示例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,
示例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');
示例10: Promise
getBody = new Promise(resolve => {
raw({ type: "*/*" })(req as any, res as any, () => resolve(req.body));
});
示例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)
示例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}
示例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);
});