Evangelos
Evangelos

Reputation: 67

How to render to a page A, data that are being posted through a form from page B using Node-express?

The problem

Hi people. I have been strangling for the past half an hour trying to solve the rending method. The problem is that I keep getting a specific ERROR 'Cannot get a specific URL' when I post data through a form from Page A and want to render these data in Page B. Although i am using POST i keep getting the data in the URL.

Image 1/3 Image 2/3 Image 3/3

 // Import core packages
    const express = require( "express" );
    const path = require( "path" );
    const bodyParser = require( "body-parser" );

    // Declare global constants
    const app = express();
    const users = [];

    // Register a template engine
    app.set( "view engine" , "ejs" );
    app.set( "views" , "templates" );

    // Middleware

    app.use( bodyParser.urlencoded( {
        extended : false
    } ) );

    app.get( "/" , ( req , res , next ) => {

        res.render( "index" , { pageTitle : "Home Page" } );

    } );

    app.get( "/users" , ( req , res , next ) => {

        res.render( "users" , { pageTitle : "Users Page" , users } );

    } );

    app.post( "/add-user" , ( req , res , next )=> {

        users.push( { username : req.body.username } );
        res.redirect( "/users" );

    } );

    // Server listening
    app.listen( 3000 );

users.js users.ejs index.js index.js

UPDATED

The problem was in the form structure.

It should be method="POST" instead of type="POST".

Upvotes: 0

Views: 37

Answers (1)

miha shadep
miha shadep

Reputation: 11

Use method get and take req.query.username. Try like this:

app.get( "/add-user" , ( req , res , next )=> {

    users.push( { username : req.query.username } );
    res.redirect( "/users" );

} );

Upvotes: 1

Related Questions