How can a jQuery Ajax call be made from within Node.js? app.js outputs the following error:
$.ajax is not a function
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
});
Use request or axios or even the core http module in node not jQuery.
An example using request:
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
});
I don't think jquery ajax is supported, but you can use something like ajax-request if you want jquery-like ajax syntax: https://www.npmjs.com/package/ajax-request . Or just use request https://github.com/request/request
You're not suppose to use jQuery inside node. They do different things, node is for back-end and jQuery for front end.
If you need to make an API call use request
And here the sample to use it:
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();
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.