1.0.6 • Published 2 months ago

node-xmlhttprequest v1.0.6

Weekly downloads
-
License
MIT
Repository
-
Last release
2 months ago

node-xmlhttprequest

A spec-compliant version of XMLHttpRequest that works in NodeJS.

Install

npm i --save node-xmlhttprequest

Quick Start

import { XMLHttpRequest } from 'node-xmlhttprequest'

const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://example.com')

xhr.onreadystatechange = () => {
	if (xhr.readyState === XMLHttpRequest.DONE) {
		const html = xhr.responseText
		const statusCode = xhr.status
		const statusText = xhr.statusText
	}
}

xhr.send()

Synchronous XHR Calls

Synchronous XHR requests work too, without writing files as other packages do. Note that it does use worker threads.

Warning This option is only left in for compatibility reasons. It is not recommended for any reason as it will block the thread.

import { XMLHttpRequest } from 'node-xmlhttprequest'

const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://example.com', false) // <-- note the false parameter
xhr.send()

assert(xhr.readyState === XMLHttpRequest.DONE)
const html = xhr.responseText
// ...

Relative URLs

Note A relative URL is a URL that only contains a path.

Relative URLs do not behave the same as the browser. You must use undici to set a relative url, otherwise an error will be thrown.

import { XMLHttpRequest } from 'node-xmlhttprequest'
import { setGlobalOrigin } from 'undici'

setGlobalOrigin('https://example.com')

const xhr = new XMLHttpRequest()
xhr.open('GET', '/api/ping')

xhr.onreadystatechange = () => {
	if (xhr.readyState === XMLHttpRequest.DONE) {
		xhr.responseURL // https://example.com/api/ping
	}
}

xhr.send()
1.0.6

2 months ago

1.0.5

2 months ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago