Skip to content

Instantly share code, notes, and snippets.

@snehesht
Created July 17, 2018 15:10
Show Gist options
  • Save snehesht/269d8f1db7be948b6f5366109c60b9c1 to your computer and use it in GitHub Desktop.
Save snehesht/269d8f1db7be948b6f5366109c60b9c1 to your computer and use it in GitHub Desktop.
Mock Server
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// app.use(function (req, res, next) {
// req.rawBody = '';
// req.setEncoding('utf8');
// req.on('data', function (chunk) {
// req.rawBody += chunk;
// });
// req.on('end', function () {
// console.log(req.rawBody)
// next();
// });
// });
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
const parseRequest = async (req) => {
if (req.query && req.query.delay) {
await new Promise((resolve) => setTimeout(resolve, parseInt(req.query.delay)));
}
const data = {
method: req.method,
headers: req.headers,
data: req.data,
body: req.body,
params: req.params,
query: req.query,
url: req.url,
};
console.log('BODY', data)
return data
}
app.get('*', async (req, res) => res.send(await parseRequest(req)))
app.post('*', async (req, res) => res.send(await parseRequest(req)))
app.put('*', async (req, res) => res.send(await parseRequest(req)))
app.delete('*', async (req, res) => res.send(await parseRequest(req)))
app.listen(3000, () => console.log('Example app listening on port 3000!'))
{
"name": "mockserver",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment