简体   繁体   中英

Sending http post and get request in NODEJS from client side using script

I am doing a small project on NodeJs. Actually I have a system where a user presses a certain button and upon pressing the button, a certain action is performed on the User Interface(ie: modification in HTML). Besides that I want to save the users history as well in the database. As in which command or button the user has pressed. How can I do it in Nodejs, on the client side, as I can not use the require("http") function on the client side. I am using mogoodb (Modulus online database) to save the data. And I have written a post request(on the server side) for saving the data, which works perfectly.

var Record = require('../app/models/record');
app.post('/saveuserhistory', function(req, res, next) {

  var newRecord            = new Record();
  newRecord.email = req.loggedinUser;
  newRecord.commands = "test_command";
  newRecord.sampledata1 = "sample1";
  newRecord.sampledata2 = "sample2";    
  Record.create(newRecord, function (err, post) {
    if (err){
      return next(err)
    }
    else{
      res.json(post);
    }
  });
});
  var x = new XMLHttpRequest();

  x.onreadystatechange = function(){
    if( x.status === 200 && x.readyState === 4) {
      // Optional callback for when request completes
      console.log(x.responseText);
    }
  }

  x.open('POST', '/saveuserhistory', true);
  x.send('email=' + someUserEmail + '&someData=' + someData);

This sends a post request to current URL's /saveuserhistory endpoint, with a couple of pieces of data. I recommend using jQuery's $.ajax() method, or Angular's $http for cleaner syntax and more cross-browser capability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM