简体   繁体   English

用于 HTTP 请求的可移植 JavaScript

[英]Portable JavaScript for HTTP requests

Is it possible to write JavaScript code to make HTTP requests such that the the same code can be used on multiple runtimes, with a suitable utility library?是否可以编写 JavaScript 代码来发出 HTTP 请求,以便相同的代码可以在多个运行时使用合适的实用程序库? In this case, it would be desirable if the code could work on node.js, Google App Script and as a Google Chrome extension or ChromeOS app.在这种情况下,如果代码可以在 node.js、Google App Script 和 Google Chrome 扩展程序或 ChromeOS 应用程序上工作,那将是可取的。

The problem is that these different runtimes have different kinds of APIs and different capabilities to accomodate programming styles.问题是这些不同的运行时有不同种类的 API 和不同的能力来适应编程风格。 App Script provides URLFetchApp, which is synchronous. App Script 提供了同步的 URLFetchApp。 Chrome and other browsers support XMLHttpRequst, which is asynchronous. Chrome 和其他浏览器支持 XMLHttpRequst,它是异步的。 Node.js supports both asynchronous and synchronous programming, and varying styles can be combined using fibers, for example. Node.js 支持异步和同步编程,例如可以使用纤程组合不同的风格。 However, fibers are not supported on other runtimes.但是,其他运行时不支持纤程。 Google App Script, on the other hand, does not seem to support plugging in asynchronous code using async/await.另一方面,Google App Script 似乎不支持使用 async/await 插入异步代码。

It seems that it is not possible to write code that supports all these runtimes without some kind of pre-processing the code.如果不对代码进行某种预处理,似乎不可能编写支持所有这些运行时的代码。

It is possible, following those steps:可以按照以下步骤操作:

  • When serving the HTTP request abstraction you should check which HTTP methods are provided in the current environment在提供 HTTP 请求抽象时,您应该检查当前环境中提供了哪些 HTTP 方法
  • Import request abstraction normalized(IE to be always async and always return a promise)导入请求抽象标准化(IE 始终异步并始终返回承诺)
  • The request abstraction should provide the same interface to its functionality(GET/POST/DELETE/PUT/PATCH)请求抽象应该为其功能提供相同的接口(GET/POST/DELETE/PUT/PATCH)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM