首页 > 解决方案 > 如何在 Node.js 中调用 $.ajax

问题描述

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

$.ajax 不是函数

应用程序.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
});

标签: javascriptjquerynode.js

解决方案


使用 request 或 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
    });

推荐阅读