You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A simple GET request, read the response body as text:
const{ request }=require('undici')asyncfunctiongetRequest(port=3001){// A simple GET requestconst{
statusCode,
headers,
body
}=awaitrequest(`http://localhost:${port}/`)constdata=awaitbody.text()console.log('response received',statusCode)console.log('headers',headers)console.log('data',data)}
A JSON POST request, read the response body as json:
const{ request }=require('undici')asyncfunctionpostJSONRequest(port=3001){constrequestBody={hello: 'JSON POST Example body'}const{
statusCode,
headers,
body
}=awaitrequest(`http://localhost:${port}/json`,{method: 'POST',headers: {'content-type': 'application/json'},body: JSON.stringify(requestBody)})// .json() will fail if we did not receive a valid json body in response:constdecodedJson=awaitbody.json()console.log('response received',statusCode)console.log('headers',headers)console.log('data',decodedJson)}
A Form POST request, read the response body as text:
const{ request }=require('undici')asyncfunctionpostFormRequest(port=3001){// Make a URL-encoded form POST request:constqs=require('node:querystring')constrequestBody={hello: 'URL Encoded Example body'}const{
statusCode,
headers,
body
}=awaitrequest(`http://localhost:${port}/form`,{method: 'POST',headers: {'content-type': 'application/x-www-form-urlencoded'},body: qs.stringify(requestBody)})constdata=awaitbody.text()console.log('response received',statusCode)console.log('headers',headers)console.log('data',data)}
A FormData request with file stream, read the response body as text
const{ request }=require('undici')const{ openAsBlob }=require('fs')asyncfunctionformDataBlobRequest(){// Make a FormData request with file stream:constformData=newFormData()formData.append('field',42)formData.set('file',awaitopenAsBlob('./index.mjs'))constresponse=awaitrequest('http://127.0.0.1:3000',{method: 'POST',body: formData})console.log(awaitresponse.body.text())constdata=awaitbody.text()console.log('response received',statusCode)console.log('headers',headers)console.log('data',data)}
A DELETE request
const{ request }=require('undici')asyncfunctiondeleteRequest(port=3001){// Make a DELETE requestconst{
statusCode,
headers,
body
}=awaitrequest(`http://localhost:${port}/something`,{method: 'DELETE'})console.log('response received',statusCode)console.log('headers',headers)// For a DELETE request we expect a 204 response with no body if successful, in which case getting the body content with .json() will failif(statusCode===204){console.log('delete successful')// always consume the body if there is one:awaitbody.dump()}else{constdata=awaitbody.text()console.log('received unexpected data',data)}}
Cacheable DNS Lookup
Using CacheableLookup to cache DNS lookups in undici