Adding Routing
const express = require("express");
const app = express();
//set routes
app.use("/product", (req, res, next) => {
res.send("<h1> Products Page</h1>");
});
app.use("/", (req, res, next) => {
res.send("<h1>Hello From Node JS server</h1>");
});
app.listen(3000);
console.log("Server running at http://127.0.0.1:3000/");
Getting the parsed Data
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
//body Parser -> for getting data like forms
//if we need data from files there are different parsers..
app.use(
bodyParser.urlencoded({
extended: true,
})
);
/*Parsing Incoming Requests
we can use app.get and app.post for filter get & post requests
also this will help for exact match
insted of app.use <-for all requests
*/
app.get("/add-product", (req, res, next) => {
res.send(
'<form action="/product" method="POST"><input type="text"
name="title"><button type="submit">Add Product</button></input></form>'
);
});
app.post("/product", (req, res, next) => {
console.log(req.body);
by default, the request does not try to parse incoming request body to this.
so that we need to register a parser
we do that adding another middleware
before all the other middlewares(in the top)
npm install --save body-parser
//Redirecting
res.redirect("/");
});
app.use("/", (req, res, next) => {
res.send("<h1>Hello From Node JS server</h1>");
});
app.listen(3000);
console.log("Server running at http://127.0.0.1:3000/");

0 Comments