const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
// Add morgan in as middleware to log all requests
app.use(morgan('dev'));
// Add body parser to convert the JSON payload to a JavaScript Object
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (request, response) => {
const success = request.query.success;
if (success === 'true') {
response.json({ message: 'Your query parameter worked!', successValue: success });
} else {
response.status(400).json({ message: 'You must supply a query parameter' });
}
});
app.post('/', (request, response) => {
response.json(request.body);
});
app.listen(port, () => {
console.log(`Server listening on port ${port}!`);
});
{
"name": "express-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4",
"morgan": "^1.9.1"
}
}