app.use() :
The app.use()
function adds a new middleware to the app. Essentially, whenever a request hits your backend, Express will execute the functions you passed to app.use()
in order.
app.use(express.json())
express.json()
is a built in middleware function in Express starting from v4.16.0. It parses incoming JSON requests and puts the parsed data in req.body
.req.body
won't work if we do not use thisapp.use(express.json()); // parses incoming JSON requests and puts the parsed data in `req.body`
/* ------------------------------------------------------ */
// JSON.parse() is used to convert JSON to object
const tours = JSON.parse(
fs.readFileSync(`${__dirname}/dev-data/data/tours-simple.json`)
);
/* ------------------------------------------------------ */
// we are converting tours JSON to string because we can't write an object to a file
fs.writeFile(
`${__dirname}/dev-data/data/tours-simple.json`,
JSON.stringify(tours),
(err) => {
// to send the response to the client that the tour has been created
res.status(201).json({
status: 'success',
data: {
tour: newTour,
},
});
}
);
// another example
return res.status(404).json({
status: 'fail',
message: 'Invalid ID',
});
/* ------------------------------------------------------ */
req.body
example :
200 : OK
201 : Created
204 : No Content (Used when deleteing something)
400 : the server cannot or will not process the request due to something that is perceived to be a client error
500 : Internal Server Error
:
const deleteUser = (req, res) => {
res.status(500).json({
status: 'error',
message: 'This route is not yet defined !'
})
}
req.params
req.body
:// json
{
"name": "Test Tout",
"duration": 10,
"difficulty": "easy"
}
then req.body
will give output as an object :
// js
{ name: 'Test Tout', duration: 10, difficulty: 'easy' }
npm i eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-config-airbnb eslint-plugin-node eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react --save-dev
.eslintrc.json
{
"extends": ["airbnb", "prettier", "plugin:node/recommended"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error",
"spaced-comment": "off",
"no-console": "warn", // eslint does not allow console.log : warn
"consistent-return": "off", // each function should return something : off
"func-names": "off",
"object-shorthand": "off",
"no-process-exit": "off",
"no-param-reassign": "off",
"no-return-await": "off",
"no-underscore-dangle": "off",
"class-methods-use-this": "off",
"prefer-destructuring": ["error", { "object": true, "array": false }],
"no-unused-vars": ["error", { "argsIgnorePattern": "req|res|next|val" }] // no-unused-vars means that we should not have any unused variables : error
}
}