Javascript 如何在 Node.js 中使用 XHR API?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34514363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:28:20  来源:igfitidea点击:

How to use XHR API in Node.js?

javascriptnode.jsxmlhttprequest

提问by Michael

This is a follow-up to my previous question

这是我上一个问题的后续

Suppose I've some javascriptcode, which runs fine on client (in a browser). This code makes a lot of XHRcalls using the browser API.

假设我有一些javascript代码,它在客户端(在浏览器中)运行良好。此代码XHR使用浏览器 API进行了大量调用。

Now I would like to run this code in node.js. Does node.jsprovide the XHRAPI as in browser ?

现在我想在node.js. 是否node.js提供XHR浏览器中的API?

采纳答案by Josh Wulf

Natively Node.js does not provide the browser XHR API. There is, however, a node module xmlhttprequestthat does.

原生 Node.js 不提供浏览器 XHR API。但是,有一个节点模块xmlhttprequest可以。

If the file is on the server itself, you can use the fs.readFile or fs.readFileSync.

如果文件在服务器本身上,您可以使用 fs.readFile 或 fs.readFileSync。

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.

如果它在远程服务器上,那么您可以使用请求之类的模块执行异步 XHR 类型的请求:https: //www.npmjs.com/package/request。这需要一些代码重写。

Probably the least re-writing of your client-side code will be if you use the xmlhttprequestnode module. It implements the browser XHR API for node.

如果您使用xmlhttprequest节点模块,您的客户端代码的重写可能最少。它为节点实现了浏览器 XHR API。

回答by Xedret

You don't really need an XHR, since you can use http.requestthat comes natively with NodeJS, with it you can send GET, POSTand PUTrequests with headers and body.

你并不真的需要一个XHR,因为你可以使用http.request与原生自带的NodeJS,有了它,你可以发送GETPOSTPUT与标题和正文的请求。

Here is the link to the documentation http.request.

这是文档http.request的链接。