在Node server中使用JQuery - TypeScript

[英]Using JQuery in Node server - TypeScript


I need to do an ajax call from node server using TypeScript. I am importing jquery as below to my class

我需要使用TypeScript從節點服務器進行ajax調用。我正在將jquery導入到我的類中,如下所示

import * as $ from "jquery"

if I hover over my implementation, it recognizes the ajax as below

如果我將鼠標停留在實現上,它會識別如下所示的ajax

enter image description here

Then, I compile this TypeScript to JavaScript. It is successful.

然后,我將這個打字稿編譯成JavaScript。它是成功的。

If I host the node server and try to access this function I am getting below error

如果我托管節點服務器並嘗試訪問此函數,我將得到下面的錯誤

TypeError : $.ajax is not a function.

I think I am missing something. I am unable to figure the things out.

我想我漏掉了什么。我搞不懂這些事情。

1 个解决方案

#1


2  

Don't do this; jQuery is for the client side, not the server

不這樣做;jQuery是面向客戶端的,而不是服務器。

As mentioned in comments, You should use a server-side HTTP client, such as the built in http.request method, or a library such as npm-fetch or Axios as your needs might dictate.

正如在注釋中提到的,您應該使用服務器端HTTP客戶端,比如在HTTP中構建的。請求方法,或如您的需求可能指示的一個庫,如npm-fetch或Axios。


However, assuming you're using the jquery npm package, please note the following quote from the package page:

但是,如果您使用的是jquery npm包,請注意包頁面中的以下引用:

For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom.

要讓jQuery在節點中工作,需要一個帶有文檔的窗口。由於節點中不存在這種窗口,因此可以使用jsdom之類的工具對其進行模擬。

What the npm package provides is a factory for instantiating jQuery injected with a faked window. They give an example of how to do that, but this part is pretty revealing:

npm包提供的是一個工廠,用於實例化使用偽造窗口注入的jQuery。他們給出了一個如何做到這一點的例子,但這部分很有啟發性:

This can be useful for testing purposes.

這對於測試很有用。

"For testing purposes" means purposes such as running unit tests in nodejs as part of your build pipeline for a client side package. Not as a general purpose library for use in node.

“用於測試目的”是指在nodejs中運行單元測試作為客戶端包的構建管道的一部分。不是用於節點的通用庫。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/12/14/61ce0e12a3931d6c2172c9f895819455.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com