简体   繁体   English

POST请求后如何刷新表单页面?

[英]How to refresh form page after POST request?

I'm working on a single page website using Netbeans (HTML5 with Node.js and Express JS). 我正在使用Netbeans(带有Node.js和Express JS的HTML5)在单页网站上工作。 The following is a sample of what I need to do (Not the real website). 以下是我需要做的示例(不是真正的网站)。

I have a form, when I click submit, I need it to post data to DB and refresh the current page that has the form. 我有一个表单,当我单击“提交”时,我需要它来将数据发布到DB并刷新具有表单的当前页面。 Right now it posts the data to DB and displays blank page (looks like empty JSON formatted page. The reason I need to refresh is I'm creating REST APIs to display data from the same DB on the same page (index.pug). 现在,它会将数据发布到数据库并显示空白页面(看起来像是空的JSON格式的页面。我需要刷新的原因是我正在创建REST API,以在同一页面(index.pug)上显示来自同一数据库的数据。

In my case I'm using Jage/Pug instead of HTML files 就我而言,我使用的是Jage / Pug而不是HTML文件

//index.pug
form(method='post', class="form-signin")
    input(type='text',class="form-control", name='fname')
    input(type='text',class="form-control", name='lname')
    button#button(type='submit', value='Submit') ADD

Here is app.js 这是app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require("body-parser");
const pg = require('pg');
const config = {
user: 'postgres',
database: 'postgres',
    password: 'password',
    port: 5432,
    idleTimeoutMillis: 30000// (30 seconds) how long a client is allowed to remain idle before connection being closed
};
const pool = new pg.Pool(config);

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next){ //This is so I can use the pool in routes js files
        req.pool = pool;
        next();
    });

app.use('/', indexRouter);
app.use('/users', usersRouter);

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

// catch 404 and forward to error handler
app.use(function(req, res, next) {
   next(createError(404));
});


// error handler
app.use(function(err, req, res, next) {
   // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
 });

module.exports = app;

and here is routes/index.js 这是routes / index.js

var express = require('express');
var router = express.Router();
const bodyParser = require("body-parser");

router.use(bodyParser.urlencoded({extended: true}));
router.use(bodyParser.json());

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
    });
//post to database
router.post("/",function (req, res, next) {
    // Grab data from http request
    var pool = req.pool;
    const data = {fname: req.body.fname, lname: req.body.lname};

 pool.connect(function (err, client, done) {
       if (err) {
           console.log("Can not connect to the DB" + err);
           res.status(400).send(err);
           }
           client.query('INSERT INTO public.names(fname, lname) values($1, $2)', [data.fname.toUpperCase(), data.lname.toUpperCase()],
              function (err, result) {
                done();
                if (err) {
                    console.log(err);
                    res.status(400).send(err);
                }
                res.status(200).send(result.rows);
                //res.redirect(req.get('referer'));
           });
        });
    });
//Create an API display all
router.get("/api/all", function (req, res, next) {
    var pool = req.pool;

    pool.connect(function (err, client, done) {
       if (err) {
           console.log("Can not connect to the DB" + err);
           res.status(400).send(err);
       }
       client.query('SELECT * FROM public.names', function (err, result) {
            done();
            if (err) {
                console.log(err.stack);
                res.status(400).send(err);
            }
            res.status(200).send(result.rows);
       });
    });
  });

module.exports = router;

I tried doing this in jQuery: 我尝试在jQuery中执行此操作:

$('#button').click(function() {
        location.reload(true);
    });

It works but only when I click on ADD button without having any values in the input fields. 它有效,但是仅当我单击ADD按钮时,在输入字段中没有任何值时才有效。

Is it possible to reload the page after a POST request? POST请求后是否可以重新加载页面? Is there anything I'm doing wrong here? 我在这里做错什么吗?

Thank you in advance! 先感谢您!

您是否尝试过将动作参数添加到表单中?

form(method='post', class="form-signin", action="/#")

由于按钮是类型submit您不必使用Javascript处理重新加载,因为它是默认的表单提交事件行为。

EDIT: In addition to form-submit which gives away connection and empty browser DOM. 编辑:除了form-submit ,它放弃了连接和空的浏览器DOM。 In addition to that you are using res.send() which just send away data to browser and since there's no JavaScript in DOM to take care of response and response is displayed with no HTML. 除此之外,您还使用res.send() ,它将数据发送到浏览器,并且由于DOM中没有JavaScript来处理响应,因此响应没有HTML显示。

To show result in html render an other ejs with response data. 为了在html中显示结果, ejs使用响应数据render其他ejs

router/index.js : router/index.js

//post to database
router.post("/",function (req, res, next) {
  // Grab data from http request
  var pool = req.pool;
  const data = {fname: req.body.fname, lname: req.body.lname};

 pool.connect(function (err, client, done) {
   if (err) {
       console.log("Can not connect to the DB" + err);

       // This is how to display data with html
       res.render('error', {err});
       }
       client.query('INSERT INTO public.names(fname, lname) values($1, $2)', [data.fname.toUpperCase(), data.lname.toUpperCase()],
          function (err, result) {
            done();
            if (err) {
                console.log(err);

                // This is how to display data with html
                res.render('error', {err});
            }

            // This is how to display data with html
            res.render('desplayData', result.rows);
       });
    });
});

error.ejs : error.ejs

    <!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">    
        <title>Error</title>
    </head>
    <body>
        <p><%=err%></p>
    </body>
</html>

displayData.ejs : displayData.ejs

    <!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">    
        <title>Display Data</title>
    </head>
    <body>
        <p><%=rows%></p>
    </body>
</html>

Better Approach single-page application using javaScript I don't understand pug/jade so will use html 使用javaScript的更好方法的单页应用程序我不了解pug/jade因此将使用html

index.html

<!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">    
        <title>Index</title>
    </head>
    <body>
        <input id="fName" type="text">
        <input id="lName" type="text">
        <p onclick="addInfo()">Submit</p>
        <!-- No need for `form` as will use JavaScript for Single Page Application -->

        <!-- This p tag will display response -->
        <p id="response"></p>

        <!-- This p tag will display error -->
        <p id="error"></p>
        <script type="text/javascript" src="/js/jquery.min.js"></script>
        <script>
             function addInfo() {
                // JavaScript uses `id` to fetch value
                let fName               = $("#fName").val(),
                    lName               = $("#lName").val();

                $.ajax({
                    "url": "/addDetail",
                    "method": "POST",
                    "data": {fName, lName}
                })
                .then( result => {
                    // On success empty all the input fields.
                    $("#fName").val('');
                    $("#lName").val('');
                    // Message to notify success submition
                    alert("Successfully added user.");

                    let newHTML = `<span>` + result + `</span>`;

                    $("#response").html(newHTML);

                    return;
                })
                .catch( err => {
                    // Notify in case some error occured
                    alert("An error occured.");

                    let newHTML = `<span>` + result + `</span>`;

                    $("#error").html(newHTML);

                    return;
                });
            }
        </script>
    </body>
</html>

router/index.js : router/index.js

//post to database
router.post("/addDetail",function (req, res, next) {
    // Grab data from http request
    var pool = req.pool;
    const data = {fname: req.body.fname, lname: req.body.lname};

     pool.connect(function (err, client, done) {
         if (err) {
             console.log("Can not connect to the DB" + err);
             res.status(400).send(err);
         }
         client.query('INSERT INTO public.names(fname, lname) values($1, $2)', [data.fname.toUpperCase(), data.lname.toUpperCase()],
            function (err, result) {
                done();
                if (err) {
                    console.log(err);
                    res.status(400).send(err);
                 }
                 res.status(200).send(result.rows);
                 //res.redirect(req.get('referer'));
            });
       });
 });

The reason you are seeing empty page with json is you are using form submit which is not a single page application method. 您看到带有json的空白页的原因是您使用的是form submit ,而不是单页应用程序方法。 In order to stick to same page and just change html content use any JavaScript framework for UI like AngularJs, reactJs, backboneJs etc. 为了坚持到同一页面并只更改html内容,请使用UI的任何JavaScript框架,例如AngularJs,reactJs,belimberJs等。

You can also use AJAX call to submit data and stay on same page and display your response from API in same HTML by hiding and displaying different HTML tags. 您还可以使用AJAX调用来提交数据并停留在同一页面上,并通过隐藏和显示不同的HTML标签显示来自API的相同HTML响应。

I have given similar answers in different posts too check all these out: 我在不同的帖子中也给出了类似的答案,也请检查所有这些内容:

  1. how to send data to html page and how to use ajax for single page application 如何将数据发送到html页面以及如何在单页面应用程序中使用ajax
  2. how-to-render-a-html-page-form-nodejs-api-when-requested-via-ajax 如何通过ajax渲染HTML页面表单nodejs-api
  3. how-to-fetch-fields-from-request-in-node-js-using-express-framework 如何使用快递框架从节点js中获取请求的字段
  4. how-to-render-a-html-page-form-nodejs-api 如何呈现HTML页面表单nodejs-api

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

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