简体   繁体   English

如何使用Node-express呈现从页面B通过表单发布的数据到页面A?

[英]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. 问题是,当我通过页面A中的表单发布数据并希望在页面B中呈现这些数据时,我不断收到特定的错误“无法获取特定的URL”。尽管我使用的是POST,但我一直在获取URL中的数据。

图片1/3 图片2/3 图片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.js users.ejs index.js index.js index.js

UPDATED 更新

The problem was in the form structure. 问题出在表单结构中。

It should be method="POST" instead of type="POST" . 它应该是method="POST"而不是type="POST"

Use method get and take req.query.username. 使用方法get和take req.query.username。 Try like this: 尝试这样:

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

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

} );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM