NodeJS Post request using a Button

◇◆丶佛笑我妖孽 提交于 2020-01-02 04:30:09

问题


I don't know if this is possible or not. All the research I've done has shown that it is possible with a form and text input. But anyways, Using NodeJs & Express I want to be able to click a button on my webpage, and once it's clicked, it sends a post request to my Node.JS server.

Simpler way of saying it: When button is clicked, send info to the server.

Goal I'm trying to achieve: When button is clicked, it sends some sort of ID/code/anything to turn on a service from my database. (I have yet to learn how db's work so I am just trying to focus on front end.)

Code I have so far:

app.post("/send", function(req, res){
  var newID = req.body.ID;
  res.redirect("/action")
});

<form action="/send" method="POST">
    <input type="button" name="newID" placeholder="Button">
    <button>send</button>
</form>

回答1:


You do not need to use jQuery or AJAX.

Simply add an input of type submit inside the form tag so that the POST request defined by your form tag is submitted.

Your newID input should be of type text, this allows entering a value in the input field.

The newID value can be retrieved server side with req.body.newID (be sure to use the body-parser middleware).

<form action="/send" method="POST">
    <input type="text" name="newID" placeholder="Enter your ID"/>
    <input type="submit" value="Click here to submit the form"/>
</form>



回答2:


For this purposes you should use $.ajax, example:

$('button').on('click', function() {
    $.ajax({
      type: 'POST',
      url: '/send',
      data: { ID: 'someid' },
      success: function(resultData) {
         alert(resultData);
      }
    });
});


来源:https://stackoverflow.com/questions/37619516/nodejs-post-request-using-a-button

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