How to use the body-parser.text 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 westmonroe / pdf-puppeteer / example / index.js View on Github external
null,
        null,
        true
    ).catch(err => {
        console.log(err);
        res.status(500).send(err);
    });
});

// Test route
router.route('/ping').get(async function(req, res) {
    res.send('Hello World');
});

app.use(
    bodyParser.text({
        limit: '50mb'
    })
);

app.use('/api', router);

// Start the server.
var port = 3000;
http.createServer(app).listen(port);
console.log('Server listening on port ' + port);
github jimkyndemeyer / js-graphql-language-service / src / languageservice.js View on Github external
}
    }
    return root;
}

function getRootKeys(newSchema) {
    if(newSchema) {
        return Object.keys(newSchema);
    }
    return '[]';
}

// setup express endpoint for the language service and register the 'application/graphql' mime-type
const app = express();
app.use(bodyParser.json({limit: '32mb'}));
app.use(bodyParser.text({type: 'application/graphql' }));

app.all('/js-graphql-language-service', function (req, res) {

    let raw = req.get('Content-Type') == 'application/graphql';

    // prepare request data
    const command = req.body.command || req.query.command || 'getTokens';
    let env = req.body.env || req.query.env;
    if(!env) {
        if(command == 'getTokens') {
            // the intellij plugin lexer has no environment info,
            // so ensure that getTokens supports '${var}', '...${fragment}', anonymous 'fragment on' etc.
            env = 'relay';
        } else {
            // fallback
            env = 'graphql';
github strues / boldr / packages / server / src / middleware / initGraphql.js View on Github external
export default function initGraphql(app) {
  const graphqlHandler = graphqlExpress(createGraphOptions);

  const gqlMiddleware = [
    bodyParser.json(),
    bodyParser.text({ type: 'application/graphql' }),
    (req, res, next) => {
      if (req.is('application/graphql')) {
        req.body = { query: req.body };
      }
      next();
    },
  ];

  // Enable GraphiQL in the config file. Only accessible
  // during development mode by default.
  if (process.env.NODE_ENV === 'development') {
    app.use(
      '/graphiql',
      graphiqlExpress({
        endpointURL: `${config.get('server.prefix')}/graphql`,
      }),
github jnewland / mpr-6zhmaut-api / app.js View on Github external
var express = require("express");
var morgan = require("morgan");
var bodyParser = require("body-parser");
var async = require("async");

var app = express();
var logFormat = "'[:date[iso]] - :remote-addr - :method :url :status :response-time ms - :res[content-length]b'";
app.use(morgan(logFormat));
app.use(bodyParser.text({ type: '*/*' }));

const ReQuery = /^true$/i.test(process.env.REQUERY);
const UseCORS = /^true$/i.test(process.env.CORS);
const AmpCount = process.env.AMPCOUNT || 1;
const BaudRate = parseInt(process.env.BAUDRATE || 9600);
const SerialPort = require("serialport");
const Readline = require('@serialport/parser-readline')

var device = process.env.DEVICE || "/dev/ttyUSB0";
var connection = new SerialPort(device, {
  baudRate: BaudRate,
});

const parser = connection.pipe(new Readline({ delimiter: "\n", encoding: "ascii" }))

connection.on("open", function () {
github SepidSystem / OrganicUI / server / api.js View on Github external
{ customerCode:id,customerName: `Title${id}`, id });

router.get('/customer', (req, res) => res.json({
    totalRows: 1000000, rows:
        Array.from({ length: req.query.rowCount || 10 }, (_, idx) => customers[+req.query.startFrom + idx + 1] || generateCustomer(+req.query.startFrom + idx + 1))
}
));
router.get('/customer/:id',
    (req, res) => res.json(customers[req.params.id] || generateCustomer(req.params.id)));
router.put('/customer/:id', (req, res) => {
    customers[req.params.id] = req.body;
    res.json({ success: true })
});
router.post('/customer', (req, res) => (res.json({ success: true })));

router.post('/deploy/:name', bodyParser.text(),
    (req, res) => {
        const filePath = `${assetsPath}/domain/${req.params.name}.js`;
        console.log(filePath, req.body);
        fs.writeFile(filePath, req.body, 'utf-8', err => res.json(err || { success: true }));

    });
function getDomainModule(modPath) {

    let mod;
    try {
        mod = reload(path.join('./src/domain/', modPath));
    } catch (ex) {
        return { statusCode: 404, message: ex.message };
    }
    if (mod instanceof Object) {
        const orginValue = mod;
github netlify / netlify-lambda / lib / serve.js View on Github external
exports.listen = function(port, static, timeout) {
  var config = conf.load();
  var app = express();
  var dir = config.build.functions || config.build.Functions;
  app.use(bodyParser.raw({ limit: "6mb" }));
  app.use(bodyParser.text({ limit: "6mb", type: "*/*" }));
  app.use(
    expressLogging(console, {
      blacklist: ["/favicon.ico"]
    })
  );

  app.get("/favicon.ico", function(req, res) {
    res.status(204).end();
  });
  app.get("/", function(req, res) {
    res
      .status(404)
      .send(
        `You have requested the root of http://localhost:${port}. This is likely a mistake. netlify-lambda serves functions at http://localhost:${port}/.netlify/functions/your-function-name; please fix your code.`
      );
  });
github xVir / api-ai-facebook / src / app.js View on Github external
function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();

app.use(bodyParser.text({ type: 'application/json' }));

app.get('/webhook/', function (req, res) {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);
        
        setTimeout(function () {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', function (req, res) {
    try {
        var data = JSONbig.parse(req.body);
github jkriss / altcloud / lib / edit-files.js View on Github external
const app = express()

  app.use(function (req, res, next) {
    opts.logger.debug('-- edit files --')
    next()
  })

  app.use(bodyParser.raw({
    type: function(req) {
      const t = req.headers['content-type']
      return !t.includes('text') && !t.includes('json') && !t.includes('form')
    },
    limit: '10mb'
  }))
  app.use(bodyParser.urlencoded({ extended: false, type: 'application/x-www-form-urlencoded' }))
  app.use(bodyParser.text({ type: 'application/json' }))
  app.use(bodyParser.text({ type: 'text/plain' }))

  const writeFile = function (req, res, next) {
    const dst = decodeURIComponent(req.path)
    const fullPath = Path.join(opts.root, dst)
    logger.debug('writing to', dst, 'full path:', fullPath)

    logger.debug(`making sure dir is present: ${Path.dirname(fullPath)}`)
    mkdirp.sync(Path.dirname(fullPath))
    var ws = fs.createWriteStream(fullPath)
    logger.debug('req body is', req.body)
    ws.write((typeof req.body === 'string' || req.body instanceof Buffer) ? req.body : JSON.stringify(req.body))
    ws.end(function (err) {
      if (err) return next(err)
      res.sendStatus(201)
    })
github thiagobustamante / typescript-rest / src / server / server-container.ts View on Github external
private buildTextBodyParserMiddleware(bodyParserOptions: any) {
        let middleware: express.RequestHandler;
        this.debugger.build('Creating text body parser with options %j.', bodyParserOptions || {});
        if (bodyParserOptions) {
            middleware = bodyParser.text(bodyParserOptions);
        }
        else {
            middleware = bodyParser.text();
        }
        return middleware;
    }
github clay / amphora / lib / routes.js View on Github external
function addAuthenticationRoutes(router) {
  const authRouter = express.Router();

  authRouter.use(require('body-parser').json({ strict: true, type: 'application/json', limit: '50mb' }));
  authRouter.use(require('body-parser').text({ type: 'text/*' }));
  amphoraAuth.addRoutes(authRouter);
  router.use('/_users', authRouter);
}

body-parser

Node.js body parsing middleware

MIT
Latest version published 1 year ago

Package Health Score

76 / 100
Full package analysis