将 ajax 转换为 node.js

Converting ajax to node.js

本文关键字:node js 转换 ajax      更新时间:2023-09-26

我已经学会了处理ajax调用以交换从服务器到浏览器的信息,但现在我在使用http请求将我的代码转换为服务器端节点兼容的JS时遇到了很大的麻烦。我读过不同的教程,但我无法将它们适应我的代码。我简单的 JS/jQuery 函数是这样的:

function ajaxCall(data, php, callback) {
    ax = $.ajax({
        type: "POST",
        data: data,
        url: php,
        success: function (raw_data) {
            f = $.parseJSON(raw_data);
            callback(f);
        },
    });
}

我需要将其转换为带有 http 请求的纯 JS 版本以与 node.js 一起使用。感谢您的任何帮助。

编辑:我尝试了又尝试,但没有成功。这是我使用的代码,我只是在我的控制台上得到很多无意义的单词.log,也许你可以纠正它:

版本 1

var data = {"action": "update", "tN": 2155};
var request = require("request");
request.post({
    url: 'http://example.com/PHP.php',
    data: data,
    }, function(error, response, body){
    console.log(body);
    }
);

版本 2

var request = require("request");
var options = {
    method: 'POST',
    uri: 'http://example.com/PHP.php',
    data: {"action": "update", "tN": 2155},
};    
request(options, function(error, response, body) {
    if(error){
        console.log(error);
    }else{
        console.log(response);
    }
});

使用 request.js

例:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
  }
})

文件请求.js