0
votes

i wrote a code sample for express js and it is working but when I use app.post or app.get instead of app.use the code does not work and the ide (webstorm) does not recognize the app.post or app.get too

is it replaced with something in the newer versions of express or something? here is my code:

const express = require('express');
let app = express();
app.use('/addp',(req,res,next)=>{
    res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({extended:true}));
     //next line does not work 
    //if I use app.use it will work fine
app.get("/product",(req,res)=>{
    console.log(req.body);
    res.redirect('/');
})
app.use('/',(req,res)=>{
    res.send("<h1>done</h1>")
})
app.listen(3000);
2
It works at this end. I copied and pasted the code above into a local file, installed Express, and ran it. Going to http://localhost:3000/product redirected me to http://localhost:3000/ which showed me the "done" output. - T.J. Crowder

2 Answers

0
votes

Your code is working fine. For the print body, you should have to use bodyParser in express js.

   const express = require('express');
let app = express();
var bodyParser = require('body-parser')

app.use('/addp', (req, res, next) => {
  res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})

app.use(express.urlencoded({ extended: true }));
app.use(
  bodyParser.json({
    limit: "250mb"
  })
);
app.use(
  bodyParser.urlencoded({
    limit: "250mb",
    extended: true,
    parameterLimit: 250000
  })
);

app.get("/product", (req, res) => {
  res.send("Get Request")
})

app.post("/product", (req, res) => {
  console.log("-------------")
  console.log(req.body);
  console.log("-------------")
  res.send("Post Request")
})

app.use('/', (req, res) => {
  res.send("<h1>done</h1>")
})

app.listen(3000);
0
votes

It is this:

app.route('/product/').get(function (req, res) {

If u want to add multiple routes let's say api, u will do this: In some module api.js:

const apiRoutes = express.Router();
apiRoutes.get('/some', () => {});
apiRoutes.post('/some', () => {});

Then let's say your server:

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