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

后端 未结 1 1223
闹比i
闹比i 2021-01-14 00:12

Task

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

Environment

  • NodeJS
  • Express
  • <
相关标签:
1条回答
  • 2021-01-14 00:38

    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>
    
    0 讨论(0)
提交回复
热议问题