我想用 nodejs 运行一个简单网络请求, 代码如下 保存为 test.js 文件
var $ = require("jquery"); var headers = { 'Accept':'application/json', 'Authorization':'string' }; $.ajax({ url: 'https://api.flaticon.com/v2/total/icons', method: 'get', headers: headers, success: function(data) { console.log(JSON.stringify(data)); } })
初始化 note js 环境用的命令是 npm init
and npm install jqurey
之后运行node test.js
文件出现错误
$ node test.js d:\python_project\node_test\test.js:10 $.ajax({ ^ TypeError: $.ajax is not a function at Object.<anonymous> (d:\python_project\node_test\test.js:10:3) at Module._compile (internal/modules/cjs/loader.js:1151:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10) at Module.load (internal/modules/cjs/loader.js:1000:32) at Function.Module._load (internal/modules/cjs/loader.js:899:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47
我在 StackOverflow 找到了比较合适的问题 https://stackoverflow.com/questions/18271251/typeerror-ajax-is-not-a-function
里面提示的方法就是 npm instal jquery
但是我这边还是没有成功, 之前 jquery 已经安装过了,
我的文件目录是这样的
─node_modules └─jquery ├─dist ├─external │ └─sizzle │ └─dist └─src ├─ajax │ └─var ├─attributes ├─core │ └─var ├─css │ └─var ├─data │ └─var ├─deferred ├─effects ├─event ├─exports ├─manipulation │ └─var ├─queue ├─traversing │ └─var └─var
但不知道错在哪里,所以请教一下
![]() | 1 zenxds 2020-04-01 17:50:10 +08:00 jQuery 主要还是 DOM 操作,用于浏览器端,运行在 node 环境下可以使用 axios,request 等其他请求库 |
![]() | 2 acthtml 2020-04-01 17:50:25 +08:00 服务端运行不了 jquery. 服务端可用使用 axios |
![]() | 3 icanfork 2020-04-01 17:50:53 +08:00 jquery 可以跑在 nodejs 上? 你直接换成 fetch 就可以了 https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch fetch('http://example.com/movies.json') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(myJson); }); |
![]() | 4 zhuangzhuang1988 2020-04-01 17:52:20 +08:00 直接上 axios |
5 VDimos 2020-04-01 18:02:47 +08:00 via Android jquery 可以跑在 nodejs 环境了吗? ajax 在 nodejs 环境有吗? |
![]() | 6 stillsilly 2020-04-01 18:06:32 +08:00 |
![]() | 7 airyland 2020-04-01 19:27:06 +08:00 先 console 下 $,看返回什么。 |
8 onekkone 2020-04-01 20:40:41 +08:00 jq 的 ajax 是基于 XMLHttpRequest 的 node 里没有这个 |
![]() | 9 SoloCompany 2020-04-01 20:57:49 +08:00 槽点有点多 python_project / node_test node / jquery 另, jquery 在 node 环境下返回的是一个 factory, 只要你传给这个 factory 一个仿真的 window / document 对象, 则可以得到一个同样仿真的 jquery 实例 |
![]() | 10 woshichuanqilz OP 不知道是不是因为用了插件的问题, 没法给各位感谢, 这里谢谢各位的帮助, 就是在 node 中没有 jquery 的问题。 |