0

I am testing a local HTML Form sending data to an aspx application as backend. Since I have some problem with CORS (even on localhost) I am trying to emulate the Ajax request performed by jQuery with NodeJS. I don't know if this is the right way to do. In the HTML form, after the jQuery validation, this is what I do:

submitHandler: function(form) {
    $.ajax({
        url: form.action,
        type: form.method,
        data: $(form).serialize(),
        success: function(response) {
            console.log(response);
        }            
    });
    //console.log($(form).serialize())
}

and it works, until CORS ends the request. I mean that I can retrieve the data from the backend application. Instead, if I do:

function loadDoc() {    

  var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
  var xhttp = new XMLHttpRequest();

  /*var FormData = require('form-data');
  var myform = new FormData();
  myform.append('firstname', 'foo');*/

  xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
   }
  };
  xhttp.open("POST", "http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE", true);

  //which is the same string I get from .serialize() in jQuery
  xhttp.send("firstname=foo&email=some@domain.it");
}

loadDoc();

I cannot get anything from the server application. If I want to get the parameter firstname from the POST data, I get null. So, where am I wrong?

UPDATE This is the only workaround I have found useful in NodeJS:

var http = require('http');

var querystring = require('querystring');
var post_data = querystring.stringify({'firstname':'Lory'});

var post_options = {
  host: 'localhost',
  port: '1308',
  path: '/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
  method: 'POST',
  headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(post_data)
  }
};

// Set up the request
var post_req = http.request(post_options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
      console.log('Response: ' + chunk);
  });
});

// post the data
post_req.write(post_data);
post_req.end();

I had also tried with:

var request = require('ajax-request');
request.post({
  url: 'http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
  data: {'firstname':'Lory'},
  headers: {}
  }, function(err, res, body) {
     console.log(res);
   }
);

but it did not work too. I feel such an ignorant and I would like to know the differences between those 3 libraries. I have some doubts concerning the fact I must use querystring.stringify() in the working solution, because POST data are not in the URL and should not be uder the limits of query string, if I remember well.

SagittariusA
  • 4,795
  • 15
  • 57
  • 112
  • 2
    do you specifically want to get it working with vanilla Node? (libraries make this cleaner). The Node API is not the same as the browser one. – Dominic Sep 13 '17 at 10:21
  • No, I don't have any specific need. As I've said I don't know NodeJS unfortunately. I just wanted to send a standard Ajax Post Request with some data to my server. Is it possible? – SagittariusA Sep 13 '17 at 10:28
  • As per my understanding, you are trying to post data from nodejs to aspx am i right? – Sharathi RB Sep 13 '17 at 11:18
  • Yes, that's correct! – SagittariusA Sep 13 '17 at 11:19
  • Can you share your aspx piece of code too – Sharathi RB Sep 13 '17 at 11:20
  • I'm sorry but I don't have an aspx code. The backend application is built with a framework (Instand Developer) where I write pseudo cose which is compiled into a DLL executable. So all my code, events and interface methods I implement in the IDE are not real code... – SagittariusA Sep 13 '17 at 11:27

2 Answers2

1

I would like to suggest request module. while doing ajax call post, we can post the data by form or JSON format. It's based on receiver end point how they are receiving.

I hope you are trying to post form data.

 var request = require('request');
 request.post({
    url:'http://service.com/upload', 
    form: {'firstname':'Lory'}
  }, function(err,httpResponse,body){ 
     /* ... */ 
  })

If you are trying to do normal JSON post.

var request = require('request')
request({
     method: 'POST',
     uri: 'http://www.google.com',
     body:{'firstname':'Lory'}
}, function(err,httpResponse,body){ 
     /* ... */ 
})

request module provide lots of options. Play with that then you will get the better idea.

Sharathi RB
  • 787
  • 2
  • 8
  • 24
  • Thank you for your kind answer. As I had updated my post, I had already tried to use the request module but the result is the same...there's no key with a value ad the backend application. – SagittariusA Sep 13 '17 at 12:18
  • I want to know how end point (aspx) is receiving the data then only I will know how to pass value from nodejs. – Sharathi RB Sep 13 '17 at 12:49
  • Whether aspx is expecting querystring params? – Sharathi RB Sep 13 '17 at 12:54
  • I'm not sure because the code generated is not mine and I can't know how it works as this that framework is not open source and it generates itself the server application. Anyway I suppose, yes, it might expect querystring parameters because they told me the only way to send a request to that application is to append that `CMD=NUOVOORDINE` to the end of the application URL. Then, I implemented an event which should get the data from the request using some given API. But I don't know anything about the implementation. Anyway don't get mad for this. I know there are many limits... – SagittariusA Sep 13 '17 at 12:58
  • Okay fine. They have a lot of option, try one by one if you don't know about receiver point. https://stackoverflow.com/questions/16903476/node-js-http-get-request-with-query-string-parameters try this too. – Sharathi RB Sep 13 '17 at 13:09
  • Thank you, it was very kind of yours. If you want, just explain me a thing: if it is strictly asked to pass params by query string, wouldn't this nullify the advantages of a POST request, which is not supposed to have params in the URL? I hope I'm not saying rubbish, I'm just a junior developer... – SagittariusA Sep 13 '17 at 13:16
  • I will suggest if its get call go querystring, if it's post call then go for body – Sharathi RB Sep 14 '17 at 10:47
1
    <html>
    <head>

       <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
            crossorigin="anonymous"></script>
    </head>
    <body>     
    <form id="myForm" name="myForm">
                            <div>
                              <label for="comment">Comment:</label>
                              <textarea id="comment" name="comment"></textarea>
                            </div>
                           <div>
                              <label for="rating">Comment:</label>
                              <textarea id="rating" name="comment"></textarea>
                            </div>

                          <input type="submit" value="Submit!">
         </form>

        <script>

        $(document).ready(function () {
           $('form').submit(function (event) {
                        event.preventDefault();
                  //collect the form data using Id Selector what ever data you need to send to server
                        let comment=$('#comment').val();
                        let rating= $('#rating').val()

                        $.ajax({
                            url: 'replace your url',
                            data: JSON.stringify({"comment": comment, "rating": rating }),
                            processData: false,
                            type: 'POST',
                            contentType: 'application/json',
                            success: function (data) {
                                alert(data);
                            }
                        });


                    });
                })


    </script>
    </html>