Express' render/redirect does not work if the call isn't coming from a submit method in a form

自作多情 提交于 2019-12-30 10:08:12

问题


Task

Perform a POST request from a JS method, so that variable values can be sent as parameters.

Environment

  • NodeJS
  • Express
  • BodyParser
  • ejs

My first attempt

Frontend:

<html>
    <head>
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
        <script type="text/javascript">
            function postAnswer() {
                $.post('vote', { message: "hello!"}, function(returnedData) {
                    console.log("Post returned data: " + returnedData);
                });
            }
        </script>
    </head>
    <body>
        <button id='send' onClick='postAnswer()' class='btn btn-success btn-xs'>Svara</button>
    </body>
</html>

Server.js:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser());

require('./app/routes.js')(app);

app.set('view engine', 'ejs');
app.use('/public', express.static(__dirname + '/public'));

var server = require('http').createServer(app);
server.listen(8080);
console.log('Server running on port 8080...');

routes.js:

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('vote.ejs', {
            message: ''
        });
    });

    app.post('/vote', function(req, res) {
        var msg = req.body.message;
        console.log("Got POST request with message: " + msg);
        res.render('index.ejs', {
            message: ''
        });
    });
};

Result:

The render method won't render a new page. It will however return the entire 'index.ejs' file in the returnedData parameter.

Server:

Client:

Second attempt:

<html>
    <head>
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
        <script type="text/javascript">
            function postAnswer() {
                $.post('vote', { message: "hello!"}, function(returnedData) {
                    console.log("Post returned data: " + returnedData);
                });
                return false;
            }
        </script>
    </head>
    <body>
        <form action='/vote' method='post'>
            <button id='send' type='submit' onsubmit='return postAnswer()' class='btn btn-success btn-xs'>Svara</button>
        </form>
    </body>
</html>

Result:

This does work, but it's not a very clean solution.

My questions:

  1. Why doesn't the first attempt work?
  2. How can I send variables as parameters to a POST request with a nice clean solution?

回答1:


I'm not a jQuery expert, but I think the first attempt doesn't work because $.post makes an AJAX request, the same way as you would in a single-page app to interact with an API in the background.

Your second example submits a form, which is an in-browser action that performs a navigation action (as specified by the method attribute of the form). In this case, the event listener you add in jQuery is redundant, and should be removed - it's making another background POST request, before the form submits the content of its fields in its request.

As for your second question, the way to submit additional variables with a form submission (presuming that you actually want to do a navigating form submission and not an XHR background request against an API) is to use <input type="hidden"> elements.

So, to summarize, to do what you're describing in your question, your example HTML should look like this (minus the comments):

<!DOCTYPE html> <!-- only you can prevent quirks mode -->
<html>
  <head>
    <meta charset="UTF-8"> <!-- ༼ つ ◕_◕ ༽つ Give UNICODE -->
  </head>
  <body>
    <form action='/vote' method='post'>
      <input type="hidden" name="message" value="hello!">
      <button id='send' type='submit' class='btn btn-success btn-xs'>Svara</button>
    </form>
  </body>
</html>


来源:https://stackoverflow.com/questions/29212414/express-render-redirect-does-not-work-if-the-call-isnt-coming-from-a-submit-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!