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

transforming a text input into unadorned plain text

Currently, I am in the process of creating a small HTML form that consists of a single textbox input. Once the user enters text into this textbox and clicks on a button located at the end of the page, I would like the textbox to transform into normal plain ...

Browser constantly displays the message "waiting for localhost"

Within my index.js file: const express = require('express'); const router = express.Router(); // Performing tasks here router.get('/', (req, res) => { res.send('Hey! It is functioning!'); }); module.exports = router; ...

Troubleshooting: CSS Styles not loading when passed as property in MUI withStyles

I am currently working on a react component that has a specific style defined as shown below: const StyledInnerItem = withStyles((theme) => ({ bgColor: { backgroundColor: (props) => { console.log('styledInnerItem color: ', props ...

Creating an engaging user experience with a Django form

Creating a dynamic calculator <div id="calculator"> <h2>Calculate the price of sawing materials</h2> <form method="post" action="{% url 'products' %}"> {% csrf_token %} & ...

Activate the search feature in select2 to allow multiple selections

I'm looking for a way to incorporate a search box into my multi-select fields using select2. Oddly enough, while the search boxes show up as expected in single-select fields, applying the same select2() function to a multi-select field doesn't s ...

Ways to efficiently display elements in a grid in real-time

Attempting to design a layout where each row consists of 3 cards using Bootstrap's Grid layout for responsiveness. The challenge lies in the fact that the card data is stored in JSON format, and the length of the JSON Object array may vary, leading t ...

Having trouble with your computed includes not working in Vue.js? Unsure of how to fix it?

How come when I use "includes" in Vue with my v-model, Vue.js logs an error? However, if I write (.includes("blabla)), everything works fine. What could be the issue? Also, how can I return the entire array if the (if) condition will work? For example, ...

Tips for obtaining a legitimate SSL certificate for a NodeJS Express API deployed on a Windows virtual machine within a VPS server

I'm in the process of setting up a Web API using NodeJS and need to enable HTTPS support. Can anyone recommend where I can obtain a legitimate SSL certificate for this purpose? Currently, my Windows VM is running on a specific IP address, hosting a N ...

What is the best method for testing different versions of the same module simultaneously?

My goal is to distribute a module across various component manager systems like npmjs and bower. I also want to provide downloadable builds in different styles such as AMD for requirejs, commonJS, and a global namespace version for browsers - all minified. ...

Using JavaScript regular expressions for email validation criteria

Hey there, I am struggling with Regular Expressions, especially when it comes to client side validation for a specific field. Can you please help me come up with a Regular Expression that would verify if an email address is valid based on these criteria: ...

Received the error message "Material-UI: capitalize(string) expects a string argument" while implementing the snackbar feature in a React Material-UI project

While working with Material-UI, I came across an issue with the snackbar where I received an error message saying: Error: Material-UI: capitalize(string) expects a string argument. Here's a snippet of my code: this.state = { snackBarOpenVer ...

The dynamic route parameter does not currently have compatibility with languages that utilize Unicode characters apart from the English

NextJS 13 (beta) Official Documentation provides information on dynamic route parameters in this link. Clarification: app/shop/[slug]/page.js To retrieve the slug, use params.slug. Example: app/shop/this-is-shop/page.js In this case, params.slug will o ...

Creating an npm module using an external JavaScript API script

I am currently in the process of creating an npm package using code from this repository. In my possession is the "minified" js file called http_www.webglearth.com_v2_api.js, which is automatically downloaded by IntelliJ when the <script src=""> tag ...

Proper approach for mapping JSON data to a table using the Fetch API in a React.js application

Struggling to map some elements of JSON to a Table in Customers.jsx, but can't seem to figure out the correct way. How do I properly insert my Fetch Method into Customers.jsx? Specifically managing the renderBody part and the bodyData={/The JsonData/} ...

How can I prevent Chrome from constantly prompting for permission to access the camera?

I have been working on some HTML/JavaScript/WebRTC projects that involve using the webcam. Despite hosting the files from my local web server (127.0.0.1), Chrome always prompts me for permission to access the camera each time I reload the page. Is there a ...

When attempting to make a GET request, Express/Mongoose is returning a null array

I am having trouble retrieving the list of books from my database. Even though I have successfully inserted the data into Mongoose Compass, when I try to fetch it, all I get is an empty array. //Model File import mongoose from "mongoose"; cons ...

JavaScript Variables Lose Their Values

Similar Inquiry: How can I get the response from an AJAX call in a function? I have written a function that fetches numerical data from an online file. Although the file retrieval is successful (verified by the alert message), I encounter an issue whe ...

Having difficulty including the Column Name in the Jqgrid footer for sum calculation

I was working on the Jqgrid code and found a way to display the sum correctly in the footer of the grid. var colSum = $("#dataGrid").jqGrid('getCol', 'Amount', false, 'sum'); $("#dataGrid").jqGrid('footerData', &a ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Tips for refreshing a GET request within a Vue.js application

I am receiving data from my Rails API backend and I would like to automatically refresh that GET request every 15 seconds. This way, if there are any changes on the backend (for example, if a POST request is made to another route), it will reload and retri ...