How to use the body-parser function in body-parser

To help you get started, we’ve selected a few body-parser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yrahul3910 / video-sharing-site / server / server.js View on Github external
import config from "../webpack.config";

import dbUtils from "./db";
import searchUtils from "./search";

const port = 8000;
const app = express();
const compiler = webpack(config);
const illegalCharsFormat = /[!@#$%^&*()+\-=[\]{};':"\\|,.<>/?]/;
dotenv.config();

// gzip files
app.use(helmet());
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser({extended: true}));
app.use(cors());
app.use(express.static(__dirname + "/public"));
app.use("/videos", express.static(__dirname + "/../videos"));
app.use("/users", express.static(__dirname + "/../users"));

// Use Webpack middleware
app.use(require("webpack-dev-middleware")(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.get("/api/trending", (req, res) => {
    res.writeHead(200, {"Content-Type": "application/json"});

    // Define trending as videos uploaded in the last 5 days, with maximum views.
    dbUtils.init();
github jkchao / blog-service / src / main.ts View on Github external
app.useGlobalInterceptors(new LoggingInterceptor(logger), new TimeoutInterceptor());

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true
    })
  );

  // app.useGlobalGuards(new AuthIsVerifiedGuard());

  // 支持 CORS
  app.enableCors({
    credentials: true
  });
  app.use(helmet());
  app.use(bodyParser());
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100
    })
  );
  app.use(compression());

  await app.listen(config.APP_PORT, '0.0.0.0', () => {
    logger.log(config.APP_NAME + ' start: 0.0.0.0:' + config.APP_PORT);
  });
}
github jkettmann / universal-react-relay-starter-kit / server / auth / index.js View on Github external
const database = new Database()

const corsOptions = {
  origin: HOST_APP,
  methods: ['POST'],
  allowedHeaders: ['X-Requested-With', 'content-type'],
  credentials: true,
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
}

const app = express()

app.use(cors(corsOptions))
app.use(sessionMiddleware())
app.use(bodyParser())
app.use(passport.initialize())

localStrategy(app, passport, database)
facebookStrategy(app, passport, database)

// Logout only deletes the token from the cookie. An attacker owning a token could
// still access user data. See following question for approaches to this problem
// https://stackoverflow.com/questions/21978658/invalidating-json-web-tokens
app.post('/logout', (req, res) => {
  req.session.token = null
  res.status(200).json({ message: 'Logout successful' })
})

app.listen(PORT, () => {
  log(`Authentication server running on localhost:${PORT}`)
})
github microsoft / BotFramework-Composer / Composer / packages / server / src / server.ts View on Github external
const app: Express = express();

const { login, authorize } = getAuthProvider();

app.all('*', function(req: Request, res: Response, next: NextFunction) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  next();
});

app.use(`${BASEURL}/`, express.static(path.join(__dirname, './public')));
app.use(morgan('dev'));

app.use(bodyParser({ limit: '50mb' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get(`${BASEURL}/test`, function(req: Request, res: Response) {
  res.send('fortest');
});

// only register the login route if the auth provider defines one
if (login) {
  app.get(`${BASEURL}/api/login`, login);
}
// always authorize all api routes, it will be a no-op if no auth provider set
app.use(`${BASEURL}/api`, authorize, apiRouter);

app.use(function(err: Error, req: Request, res: Response, _next: NextFunction) {
  if (err) {
github TossShinHwa / CMS / new-server / src / index.js View on Github external
import comment from './resources/article/comment';
import gallery from './resources/gallery/gallery';
import board from './resources/board/board';
import user from './resources/system/user';

import login from './functions/login';
import upload from './functions/upload';

const server = odata('mongodb://localhost/cms');

// hack: persistence current all resouces for actions and functions to use.
odata.resources = server.resources;

// odata config
server.use(cors({ exposedHeaders: 'authorization' }));
server.use(bodyParser({
  uploadDir: path.join(path.dirname(__dirname), 'server/static/upload/temp'),
}));
server.use(odata._express.static(path.join(__dirname, './static')));
server.use(authorizationMiddleware);
server.use(morgan('short'));
server.use(errorHandler());

// init resources
[
  article,
  category,
  comment,
  gallery,
  board,
  user,
].map((resource) => server.use(resource));
github michaelwilcox / headfon.es / server / src / index.ts View on Github external
resolvers,
  context: (req, res) => {
    const { response } = req;
    const { user } = req.request;
    return { response, user };
  }
});

initDatabase();

passport.use(spotifyStrategy);
refresh.use(spotifyStrategy);
passport.use('jwt', jwtStrategy);

server.use(cookieParser());
server.use(bodyParser());
server.use(passport.initialize());

debug(server);

server.use('/auth/connect', middleware.spotify.redirect, () => {});
server.use('/auth/callback', middleware.spotify.base, routes.login);
server.use('/logout', routes.logout);
server.use('/app', middleware.auth, routes.app);
server.use('/user', passport.authenticate(['jwt'], { session: false }), routes.user);
server.use('/token', passport.authenticate(['jwt'], { session: false }), routes.token);

if (process.env.NODE_ENV === 'production') {
  // Serve any static files
  server.use(express.static(path.join(__dirname, '../../', 'client/build')));
  // Handle React routing, return all requests to React app
  server.get(/^\/(?!playground).*/, (req, res) => {
github jackyef / react-isomorphic-data / examples / ssr / src / server.tsx View on Github external
// hack for augmenting fetch to global
const globalAny: any = global;
globalAny.fetch = fetch;

let assets: any;

const syncLoadAssets = () => {
  // eslint-disable-next-line
  assets = require(process.env.RAZZLE_ASSETS_MANIFEST!);
};
syncLoadAssets();

const server = express();

server.disable('x-powered-by');
server.use(bodyParser());
// eslint-disable-next-line
server.use(express.static(process.env.RAZZLE_PUBLIC_DIR!));
server.use(compression());

server.get('/some-rest-api*', async (req: express.Request, res: express.Response) => {
  res.json({
    message: req.url,
    randomNumber: Math.floor(Math.random() * 100),
  });
});

server.post('/some-rest-api*', async (req: express.Request, res: express.Response) => {
  res.json({
    message: `echo-ing the stuffs you posted`,
    data: req.body,
    randomNumber: Math.floor(Math.random() * 100),
github yrahul3910 / video-sharing-site / server / server.js View on Github external
// Used for transpiling
import webpack from "webpack";
import config from "../webpack.config";

import dbUtils from "./db.js";

const port = 8000;
const app = express();
const compiler = webpack(config);
dotenv.config();

// gzip files
app.use(compression());
app.use(session({secret: process.env.SESSION_SECRET}));
app.use(bodyParser.json());
app.use(bodyParser({extended: true}));
app.use(cors());
// Use Webpack middleware
app.use(require("webpack-dev-middleware")(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.get("/*", (req, res) => {
    res.sendFile(path.join(__dirname, "../src/index.html"));
});

app.post("/api/upload", (req, res) => {
    res.writeHead(200, {"Content-Type": "application/json"});

    let form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
github adeperio / base / src / server / server.js View on Github external
var scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'", "ajax.googleapis.com", "www.google-analytics.com"];
var styleSources = ["'self'", "'unsafe-inline'", "ajax.googleapis.com"];
var connectSources = ["'self'"];

server.use(helmet.contentSecurityPolicy({
    defaultSrc: ["'self'"],
    scriptSrc: scriptSources,
    styleSrc: styleSources,
    connectSrc: connectSources,
    reportOnly: false,
    setAllHeaders: false,
    safari5: false
}));

server.use(methodOverride());
server.use(bodyParser());

//setup express sessions
server.use(cookieParser());
server.use(session({
  store: new pgSession({
    pg : pg,
    conString : Config.connectionString,
    tableName : 'session',
    schemaName: 'public'
  }),
  secret: Config.session.secret,
  resave: false,
  saveUninitialized: true,
  expires : new Date(Date.now() + 3600000), //1 Hour
  cookie: { httpOnly:true, secure: true }
}));

body-parser

Node.js body parsing middleware

MIT
Latest version published 1 year ago

Package Health Score

76 / 100
Full package analysis