【问题标题】:Sending http post and get request in NODEJS from client side using script使用脚本从客户端发送 http post 并在 NODEJS 中获取请求
【发布时间】:2016-02-22 07:58:35
【问题描述】:

我正在做一个关于 NodeJs 的小项目。 实际上,我有一个系统,用户按下某个按钮,按下按钮后,会在用户界面上执行某个操作(即:在 HTML 中进行修改)。除此之外,我还想将用户历史记录保存在数据库中。就像用户按下了哪个命令或按钮一样。 我如何在客户端的 Nodejs 中做到这一点,因为我不能在客户端使用 require("http") 函数。 我正在使用 mogoodb(模数在线数据库)来保存数据。而且我已经写了一个发布请求(在服务器端)来保存数据,效果很好。

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);
    }
  });
});

【问题讨论】:

  • 你可以先写一些代码,这通常会有所帮助
  • 如何使用脚本从客户端调用:localhost:8080/saveuserhistory。

标签: javascript jquery angularjs node.js


【解决方案1】:
  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);

这会向当前 URL 的 /saveuserhistory 端点发送一个发布请求,其中包含几条数据。我建议使用 jQuery 的 $.ajax() 方法或 Angular 的 $http 以获得更简洁的语法和更多的跨浏览器功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2017-07-04
    • 1970-01-01
    • 2019-05-31
    相关资源
    最近更新 更多