如何在Node.js中调用$.ajax



如何在Node.js中进行jQuery Ajax调用?app.js输出以下错误:

$.ajax不是一个函数

app.js

var $ = require('jQuery');
$.ajax({
url: "https://api.example.com/resource/example.json",
type: "GET",
data: {
"$limit" : 5000,
"$$app_token" : "MY_TOKEN"
}
}).done(function(data) {
// Logic
});

使用请求或axios,甚至是节点中的核心http模块,而不是jQuery。

使用请求的示例:

var request = require('request');
request({ url: 'http://api.example.com/resource/example.json’, qs: {
"$limit" : 5000,
"$$app_token" : "MY_TOKEN"
} }, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); 
// Print the response status code if a response was received
console.log('body:', body); // Print the HTTP body
});

我认为不支持jquery ajax,但如果您想要类似jquery的ajax语法,可以使用类似ajax请求的东西:https://www.npmjs.com/package/ajax-request.或者只是使用请求https://github.com/request/request

您不应该在节点内部使用jQuery。它们做不同的事情,node用于后端,jQuery用于前端。

如果您需要进行API调用使用请求

这里是使用它的样本:

var options = {
host: "the-end-point-host",
port: 80, // the port
path: '/the-path',
method: 'POST' // HTTP verb you wnat to use
};
http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
}).end();