Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XHR API in Node.js?

This is a follow-up to my previous question

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.

Now I would like to run this code in node.js. Does node.js provide the XHR API as in browser ?

like image 916
Michael Avatar asked Dec 29 '15 15:12

Michael


People also ask

Can you use XMLHttpRequest in node JS?

node-XMLHttpRequest is a wrapper for the built-in http client to emulate the browser XMLHttpRequest object. This can be used with JS designed for browsers to improve reuse of code and allow the use of existing libraries.

What is XHR in API?

XMLHttpRequest (XHR) is a JavaScript API to create AJAX requests. Its methods provide the ability to send network requests between the browser and a server.


3 Answers

You don't really need an XHR, since you can use http.request that comes natively with NodeJS, with it you can send GET, POST and PUT requests with headers and body.

Here is the link to the documentation http.request.

like image 199
Xedret Avatar answered Oct 16 '22 17:10

Xedret


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

If the file is on the server itself, you can use the fs.readFile or 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.

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.

like image 23
Josh Wulf Avatar answered Oct 16 '22 17:10

Josh Wulf


this is why we use Axios for modules. It can be used on client or server side without any dependency or code changes.

like image 25
Josh Avatar answered Oct 16 '22 16:10

Josh