The node.js express app.get and app.post are currently malfunctioning

I have encountered an issue with my Express JS code. Currently, I am using app.use and everything works perfectly. However, when I try to use app.post or app.get instead of app.use, the code stops working and my IDE (WebStorm) does not recognize these methods either.

Could it be that something has replaced app.post and app.get in newer versions of Express? Below is a snippet of 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);

Answer №1

Your code solution appears to be functioning correctly. To handle the request body in your Express.js application, make sure you are utilizing bodyParser.

   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);

Answer №2

This is how it can be done:

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

If you want to add multiple routes, for example an API, you can follow this approach: Create a module called api.js:

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

Then in your server file:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Copy and paste the code from your clipboard into various input fields

I have been searching for a Vanilla JavaScript solution to copy and paste code into multiple input fields. Although I have found solutions on the internet, they are all jQuery-based. Here is an example of such a jQuery solution <input type="text" maxl ...

Retrieving an array from the $.get() method within multiple nested loops

I'm currently working on a jQuery plugin that takes an array of JSON files and needs to compile them into one large array. While each part of the code works individually, I'm facing issues when trying to integrate them together and return the ne ...

Access JSON file without considering any custom comments

Is there a way to extract the JSON data from 'file.json' without including any comments? # Comment01 # Comment02 { "name": "MyName" } I have tried using this code snippet: var fs = require('fs'); var obj; fs.readFile('./file. ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

Authentication via Passport immediately following the completion of a new user registration

Upon submission of the /register form, I am looking to instantly authenticate and log in a user. My goal is for users to register and seamlessly be directed to the dashboard without needing to re-enter their login information. The server is powered by Pas ...

Running a child process within an express js route

I have a problem where I am trying to execute a child process within my Express JS route and then return a JSON message with the output of this process as the message value. However, I am currently experiencing an issue where the stdout value is coming bac ...

Struggling to increment the badge counter in a React Typescript project

I'm a bit unsure about where to apply the count in my Badge Component. The displayValue should include the count, but I'm struggling with how to implement it. UPDATE: The counter is now in place, but when I decrease the count and it reaches 0, t ...

Instructions for enabling the touch slider feature in the Igx carousel component with Angular 6 or higher

Looking to enable the touch slider for Igx carousel using angular 6+? I am trying to implement the igx carousel for image sliding with reference from a stackblitz demo (https://stackblitz.com/edit/github-j6q6ad?file=src%2Fapp%2Fcarousel%2Fcarousel.compone ...

Why does my GET request to "/sell" always result in a redirect to "/" with a HTTP status code 302?

When I am logged out and make a "GET" request to "/sell", I get redirected to "/user/login" as expected. However, when I am logged in and make a GET request to "/sell", I am always redirected to the homepage ("/") instead of the "/sell" page. How can I ens ...

Creating a bezel design in CSS or Vue: A step-by-step guide

Embedding: Is there a CSS property that can be used to create the same angle as shown in the layout? I looked everywhere in the program but couldn't find this specific property. Tried searching here !: ...

How can you provide arguments to a mock function?

While using jest for unit testing, I am encountering the following line of code: jest.mock('../../requestBuilder'); In my project folder, there is a __mocks__ subfolder where I have stored my mock requestBuilder.js file. The jest unit test i ...

The previous button on Owl Carousel seems to be malfunctioning after navigating from a different page

In my case, I have two distinct pages: let's call them the first and second pages. On the first page, I utilize an owl carousel slider with a tag that links to a specific slide on the second page's owl carousel slider using an ID. Meanwhile, on ...

Is it possible to disable 'rtl' using {flip: false}?

I am attempting to replicate the behavior demonstrated in the MUI docs at this link. When switching from 'ltr' to 'rtl', the 'Affected' content flips sides while the 'Unaffected' remains unaffected. To illustrate th ...

Coordinate the timing of CSS animation with the loading of the page

Despite the abundance of similar questions, none have quite addressed my specific query. I've created a preloader using CSS animation and I want it to synchronize perfectly with the page load. While I can trigger the animation on page load, I'm s ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

The Angular routing feature seems to be malfunctioning

I have encountered a frustrating issue with AngularJS routing and despite countless searches for solutions, I am still facing the same problem. In my root folder at c:\intepub\wwwroot\angular\, I have three files that I am testing under ...

Mongoose - embedded documents are stored as text data

Within my node application, I have a designation model that utilizes the following Schema: var DesignationSchema = new Schema({ _id : ObjectId, designation : String }); This DesignationSchema is then embedded within the users Schema. var UserSch ...

Ways to identify an element within a webpage

I'm currently working on creating a chrome extension that can detect the presence of specific elements on a webpage. The goal is to have this extension automatically run every time a new page is opened and display a popup message if the element is fou ...