如何在 Node.js 中使用 XHR API? [英] How to use XHR API in Node.js?
问题描述
这是我之前的问题的后续
假设我有一些 javascript
代码,它们在客户端(在浏览器中)运行良好.此代码使用浏览器 API 进行了大量 XHR
调用.
Suppose I've some javascript
code, which runs fine on client (in a browser). This code makes a lot of XHR
calls using the browser API.
现在我想在 node.js
中运行这段代码.node.js
是否提供浏览器中的 XHR
API?
Now I would like to run this code in node.js
. Does node.js
provide the XHR
API as in browser ?
推荐答案
Node.js 本身不提供浏览器 XHR API.但是,有一个节点模块 xmlhttprequest 可以.
Natively Node.js does not provide the browser XHR API. There is, however, a node module xmlhttprequest that does.
如果文件在服务器上,您可以使用 fs.readFile 或 fs.readFileSync.
If the file is on the server itself, you can use the fs.readFile or fs.readFileSync.
如果它在远程服务器上,那么您可以使用类似 request 的模块执行异步 XHR 类型的请求:https://www.npmjs.com/package/request.这需要重写一些代码.
If it is on a remote server, then you can do an asynchronous XHR type request using a module like request: https://www.npmjs.com/package/request. This requires some rewriting of code.
如果您使用 xmlhttprequest 节点模块.它为 node 实现了浏览器 XHR API.
Probably the least re-writing of your client-side code will be if you use the xmlhttprequest node module. It implements the browser XHR API for node.
这篇关于如何在 Node.js 中使用 XHR API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!