How to send form data to server

谁说我不能喝 提交于 2021-02-10 13:17:27

问题


I want to build a small website. I have backend almost done but i can't find how can i send form data to server. Here is my attempt and i want to send the data to localhost running at port 3000 for example:

jQuery('#signUp-Form').on('submit',function(e){
    e.preventDefault();
    console.log('Sending data');
    var name = jQuery('[name = username]').val();
//    socket.emit('sign-up',{
//      username: jQuery('[name = username]').val(),
//      password: jQuery('[name = password]').val()
//    });
});

I can do with socket.io but however i want to use POST,GET etc and at server side i built my server with express.

I can retrieve the name from the field into the var name and now i want to send it to server: here is the function which will handle this request. Only first two lines:

app.post('/login',(req,res) => {
  var body = _.pick(req.body, ['username', 'password']);

Now my question is how can i send data in such format so that '/login' matches with pattern and req.body contains the name only.

It is the basic question but i don't see anywhere how can i do this.


回答1:


Khan, it looks like you are attempting two methods of form submission: non-AJAX and AJAX. From your question it's not apparent which method is intended, but I will show both methods:

Non-AJAX

Using <form action="/login" method="POST">:

<form id="myform" action="/login" method="POST">
    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit">login</button>
</form>

This method will refresh the page and make a POST request to /login sending the url encoded data like:

username=nha&password=asonteu

AJAX

With AJAX, the page won't refresh, and you must send the data programmatically:

$( "#myform" ).on( "submit", function( event ) {
    event.preventDefault();
    let data = $( this ).serialize();
    //make our request here
    $.post( "/login", function( data ) {
        console.log(data);
    });
});

serialize() also url encodes the form data.

Your server must handle any expected data format (to extract the fields properly). URL encoding is useful, but later you will see JSON or perhaps protobufs. It really doesn't matter which format you use as long as both the client and server agree.

NOTE: With POST, the data will be in the request body

I hope this helps!



来源:https://stackoverflow.com/questions/53089101/how-to-send-form-data-to-server

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