gpt4 book ai didi

javascript - 使用脚本从客户端发送http post并在NODEJS中获取请求

转载 作者:搜寻专家 更新时间:2023-11-01 00:00:49 26 4
gpt4 key购买 nike

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

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

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

关于javascript - 使用脚本从客户端发送http post并在NODEJS中获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33816374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com