---
title: Richieste HTTP
project: Total.js V5
version: 0.0.20
section: reference
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/http-requests/
updated: 2026-11-18T16:57:29.576Z
---

# Richieste HTTP

> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() e Total.download().

Le funzioni globali e la classe `RESTBuilder` per le richieste HTTP verso altri servizi. Per un'introduzione con esempi leggi la guida [Richieste HTTP](../../guides/http-requests/). Il client WebSocket `OPENCLIENT()` ha una pagina propria: [OpenClient](../openclient/).

## API

### REQUEST(options, [callback])

Type: `method`

Invia una richiesta HTTP con il pieno controllo delle opzioni.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options.url` | `String` | yes |  | L'URL della richiesta. Le credenziali nell'URL (`https://user:password@host/`) vengono inviate come `Authorization: Basic`; i caratteri codificati con percentuale al loro interno vengono prima decodificati. |
| `options.method` | `String` | no | `'GET'` | Il metodo HTTP in maiuscolo. |
| `options.headers` | `Object` | no |  | Header della richiesta. L'oggetto viene copiato, quindi il tuo oggetto non viene modificato. |
| `options.type` | `String` | no |  | Imposta `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` o `'text'`, `'raw'` (`application/octet-stream`). |
| `options.body` | `String|Buffer` | no |  | Il body della richiesta. Una stringa viene inviata come UTF-8; `Content-Length` viene impostato per te. |
| `options.query` | `Object|String` | no |  | Aggiunto all'URL come query string. |
| `options.cookies` | `Object` | no |  | Cookie da inviare, come `{ name: value }`. |
| `options.cook` | `Boolean` | no |  | Salva i cookie della response in `options.cookies`, così lo stesso oggetto options li invia con la richiesta successiva. |
| `options.timeout` | `Number` | no | `8000` | Timeout in millisecondi; `0` lo disattiva. |
| `options.encoding` | `String` | no | `'utf8'` | Codifica di un body testuale. `'binary'` restituisce un `Buffer`. |
| `options.xhr` | `Boolean` | no |  | Aggiunge `X-Requested-With: XMLHttpRequest`. |
| `options.files` | `Array` | no |  | File per una richiesta `multipart/form-data`: `[{ name, filename, buffer \| path \| url }]`. `options.body` è quindi un oggetto di campi aggiuntivi del form. |
| `options.compress` | `String` | no |  | Comprime il body: `'gzip'` o `'deflate'`, e imposta `Content-Encoding`. |
| `options.encrypt` | `String` | no |  | Una chiave: il body viene cifrato con essa e la risposta testuale viene decifrata con essa. |
| `options.writer` | `Function` | no |  | `function(req)` scrive il body da sé: riceve la richiesta di Node.js, scrive i dati e chiama `req.end()`. `body` e `files` non vengono quindi usati. |
| `options.custom` | `Boolean` | no |  | Restituisce `response.stream` invece di leggere il body. |
| `options.noredirect` | `Boolean` | no |  | Non segue i redirect; la callback riceve la risposta `301`/`302`. |
| `options.keepalive` | `Boolean` | no |  | Usa un agent keep-alive condiviso (uno per HTTP, uno per HTTPS). |
| `options.resolve` | `Boolean` | no |  | Risolve l'hostname con una cache DNS. `options.dnscache` fa lo stesso. Viene saltato per `localhost` e gli indirizzi IP. |
| `options.proxy` | `String` | no |  | Un proxy per questa richiesta, come `'host:port'` o `'http://host:port'`. Con `http://user:password@host:port` le credenziali vengono inviate come `Proxy-Authorization: Basic`. |
| `options.insecure` | `Boolean` | no |  | Accetta certificati TLS non validi o autofirmati. |
| `options.key` | `Buffer` | no |  | Chiave TLS del client. |
| `options.cert` | `Buffer` | no |  | Certificato TLS del client. |
| `options.dhparam` | `Buffer` | no |  | Parametri Diffie-Hellman TLS. |
| `options.unixsocket` | `Object` | no |  | `{ socket, path }` per inviare la richiesta attraverso un socket Unix invece di `url`. |
| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` per ogni chunk ricevuto. |
| `options.onprogress` | `Function` | no |  | `function(percentage)`; la percentuale è nota solo con `Content-Length`. |
| `options.callback` | `Function` | no |  | `function(err, response)`, al posto del secondo argomento. |
| `callback` | `Function` | no |  | `function(err, response)`. |

Returns: `Promise` Una promise quando non viene fornita alcuna callback; altrimenti nulla.

Invia una richiesta HTTP descritta da `options`. La callback riceve `(err, response)`; senza callback (nell'argomento o in `options.callback`) restituisce una promise che si risolve con `response`.

L'oggetto response ha `status`, `headers`, `body`, `host`, `origin` (gli indirizzi IP risolti quando la cache DNS è attiva) e `cookies` (i cookie raccolti nei redirect). `body` è una stringa per i tipi `text/*` e `application/*` (decodificata con `encoding`) e un `Buffer` per gli altri tipi, oppure sempre un `Buffer` con `encoding: 'binary'`. Il body non viene interpretato: usa `RESTBuilder` o `AJAX()` per questo.

Con `custom: true` la callback viene eseguita appena arrivano gli header e la response ha `stream` (la response di Node.js) invece di `body`.

Errori: un errore di rete passa l'oggetto errore con `response.status === 0`; un timeout scaduto passa `'408: Request Timeout'` con `response.status === 408`; più di quattro redirect passano `'Too many redirects'`; un URL senza hostname passa `'Invalid hostname'`, e una stringa che non è un URL lancia `TypeError: Invalid URL`. Un codice di stato `400` o superiore non è un errore: controlla `response.status`.

I redirect `301` e `302` vengono seguiti (i cookie del redirect vengono inviati alla posizione successiva). Le richieste usano il proxy della chiave di configurazione `$proxyrequest` quando è impostata, tranne che per `localhost`, `127.0.0.1` e `0.0.0.0`.

Example: POST JSON
```js
REQUEST({
	url: 'https://api.example.com/orders/',
	method: 'POST',
	type: 'json',
	body: JSON.stringify({ id: 'p100', count: 2 })
}, function(err, response) {
	if (err || response.status !== 200)
		return;
	var order = response.body.parseJSON();
});
```

Example: Con una promise
```js
var response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });
console.log(response.status, response.body);
```

Example: Caricare un file
```js
REQUEST({
	url: 'https://files.example.com/upload/',
	method: 'POST',
	files: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],
	body: { folder: 'reports' }
}, console.log);
```

Example: Leggere uno stream
```js
REQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {
	if (!err)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));
});
```

Example: Scrivere il body da te
```js
REQUEST({
	url: 'https://api.example.com/import/',
	method: 'POST',
	type: 'plain',
	writer: function(req) {
		for (var line of lines)
			req.write(line + '\n');
		req.end();
	}
}, console.log);
```

### AJAX('METHOD url', [data], [callback])

Type: `method`

Invia una richiesta JSON e restituisce la risposta analizzata.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | `'METHOD url'`, per esempio `'POST https://example.com/api/'`. |
| `data` | `Object` | no |  | Dati inviati come JSON. |
| `callback` | `Function` | no |  | `function(err, response, meta)`. |

Returns: `Promise` Una promise quando non viene fornita alcuna callback.

Invia una richiesta e interpreta la risposta. Il primo argomento è il metodo e l'URL separati da uno spazio; senza metodo è `GET`. `data` viene inviato come body JSON. L'header `X-Requested-With: XMLHttpRequest` viene sempre aggiunto.

La risposta viene interpretata in base al suo `Content-Type`: JSON (`application/json`, `text/json`), dati URL-encoded e XML (`application/xml`, `text/xml`) diventano oggetti; gli altri tipi vengono restituiti come body grezzo. Un documento XML diventa un oggetto piatto: i nomi degli elementi annidati vengono uniti con `_` (`order_name`), gli elementi ripetuti danno un array e gli attributi di un elemento sono in un oggetto sotto il suo nome con `__` (`order__`). Un body XML vuoto dà `{}`. La callback riceve `(err, response, meta)`, dove `meta` contiene `status`, `headers` e `host`.

Per uno stato `400` o superiore, `err` è il body interpretato (per un servizio Total.js l'array degli errori) e `response` è `null`. Senza callback la funzione restituisce una promise che si risolve con il body interpretato e viene rifiutata con `err`; un array di errori Total.js diventa un `Error` il cui messaggio contiene i messaggi di errore.

Example: Callback
```js
AJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {
	console.log(meta.status, response);
});
```

Example: Promise
```js
var products = await AJAX('GET https://api.example.com/products/?page=1');
```

Example: Risposta XML
```js
// the service answers <order id="100"><name>Book</name><items><item>A</item><item>B</item></items></order>
var order = await AJAX('GET https://api.example.com/orders/100/');
// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }
```

### DOWNLOAD(url, filename, [callback], [timeout])

Type: `method`

Scarica un file remoto su disco.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Object` | yes |  | L'URL, oppure `{ socket, path }` per un socket Unix. |
| `filename` | `String` | yes |  | Il percorso del file di destinazione. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `timeout` | `Number` | no | `8000` | Timeout in millisecondi. |

Returns: `Promise` Una promise quando non viene fornita alcuna callback.

Scarica `url` e scrive il body in `filename`. La callback viene eseguita quando il file è scritto, con `(err, response)`. `response` contiene `status`, `headers`, `origin`, `filename` e `size` (il numero di byte scritti). Il body viene salvato per ogni codice di stato, quindi controlla `response.status`.

`url` può essere anche un oggetto `{ socket, path }` per un socket Unix. Le risoluzioni DNS vengono messe in cache. `timeout` è in millisecondi (8 secondi se non impostato). Senza callback la funzione restituisce una promise che si risolve con `response`.

Example: Scaricare un'immagine
```js
DOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
	if (!err && response.status === 200)
		console.log('Saved', response.filename);
});
```

Example: Promise
```js
var response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));
```

### Total.download(url, filename, [callback], [timeout])

Type: `method`

Il metodo del framework dietro DOWNLOAD().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Object` | yes |  | L'URL, oppure `{ socket, path }` per un socket Unix. |
| `filename` | `String` | yes |  | Il percorso del file di destinazione. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `timeout` | `Number` | no | `8000` | Timeout in millisecondi. |

Returns: `Promise` Una promise quando non viene fornita alcuna callback.

La stessa funzione di `DOWNLOAD()`. Scarica `url` e scrive il body in `filename`. La callback viene eseguita quando il file è scritto, con `(err, response)`. `response` contiene `status`, `headers`, `origin`, `filename` e `size` (il numero di byte scritti). Il body viene salvato per ogni codice di stato, quindi controlla `response.status`.

`url` può essere anche un oggetto `{ socket, path }` per un socket Unix. Le risoluzioni DNS vengono messe in cache. `timeout` è in millisecondi (8 secondi se non impostato). Senza callback la funzione restituisce una promise che si risolve con `response`.

Example: Download
```js
Total.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {
	console.log(err, response.status);
});
```

### new RESTBuilder([url])

Type: `class`

Un builder per le richieste verso servizi REST.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | L'URL della richiesta. |

Returns: `RESTBuilder` Un nuovo builder.

Una classe globale. Un nuovo builder ha il metodo `GET`, un timeout di 10 secondi, la cache DNS attiva, l'header `user-agent: Total.js/v...` e `accept: application/json, text/plain, text/plain, text/xml`. Non viene inviato nulla finché non chiami `callback()`, `promise()`, `stream()` o `exec()`.

Di solito inizi con un helper statico: `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` o `make()`. `RESTBuilder.url(url)` equivale a `new RESTBuilder(url)`.

Example: Creare un builder
```js
var builder = RESTBuilder.url('https://api.example.com/users/');
builder.header('X-Token', CONF.apitoken);
builder.callback(console.log);
```

### RESTBuilder.make(fn)

Type: `method`

Crea un builder e lo passa a una funzione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(builder)`. |

Returns: `RESTBuilder` Il nuovo builder.

Crea un builder senza URL e chiama `fn(builder)`. Imposta l'URL con `builder.url()`. Il metodo di istanza `builder.make(fn)` chiama `fn` con il builder come `this` e come argomento, per impostazioni riutilizzabili.

Example: Costruire una richiesta
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/users/');
	builder.post({ name: 'Peter' });
	builder.callback(console.log);
});
```

### RESTBuilder.GET(url, [data])

Type: `method`

Crea una richiesta GET.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL. |
| `data` | `Object` | no |  | Inviato come query string. |

Returns: `RESTBuilder` Un nuovo builder.

Crea un builder con il metodo `GET`; `data` diventa la query string. Per una richiesta `HEAD` usa `RESTBuilder.HEAD(url)`: non ha dati, il valore analizzato è un oggetto vuoto e leggi `output.status` e `output.headers`.

Example: Query string
```js
RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {
	console.log(response);
});
```

Example: HEAD
```js
RESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {
	console.log(output.status, output.headers['last-modified']);
});
```

### RESTBuilder.POST(url, [data])

Type: `method`

Crea una richiesta POST.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL. |
| `data` | `Object` | no |  | Inviato come body JSON. |

Returns: `RESTBuilder` Un nuovo builder.

Crea un builder con il metodo `POST`; `data` viene inviato come JSON. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` e `RESTBuilder.DELETE()` funzionano allo stesso modo con i rispettivi metodi.

Example: POST JSON
```js
RESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {
	console.log(order.id);
});
```

### RESTBuilder.PUT(url, [data])

Type: `method`

Crea una richiesta PUT.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL. |
| `data` | `Object` | no |  | Inviato come body JSON. |

Returns: `RESTBuilder` Un nuovo builder.

Crea un builder con il metodo `PUT`; `data` viene inviato come JSON.

Example: PUT
```js
RESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
```

### RESTBuilder.PATCH(url, [data])

Type: `method`

Crea una richiesta PATCH.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL. |
| `data` | `Object` | no |  | Inviato come body JSON. |

Returns: `RESTBuilder` Un nuovo builder.

Crea un builder con il metodo `PATCH`; `data` viene inviato come JSON.

Example: PATCH
```js
RESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
```

### RESTBuilder.DELETE(url, [data])

Type: `method`

Crea una richiesta DELETE.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL. |
| `data` | `Object` | no |  | Inviato come body JSON. |

Returns: `RESTBuilder` Un nuovo builder.

Crea un builder con il metodo `DELETE`; `data` viene inviato come JSON.

Example: DELETE
```js
RESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);
```

### RESTBuilder.API(url, name, [data])

Type: `method`

Chiama un endpoint API di un'applicazione Total.js.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL dell'endpoint API. |
| `name` | `String` | yes |  | Il nome dell'operazione API. |
| `data` | `Object` | no |  | I dati dell'operazione. |

Returns: `RESTBuilder` Un nuovo builder.

Crea una richiesta `POST` per una route API di Total.js (`ROUTE('API /api/ ...')`). Il body è JSON: `{ schema: name, data: data }`. `name` è il nome dell'API con parametri facoltativi, per esempio `'products_detail/p100'`. `builder.get(query)` mantiene il `POST` e invia la query nel body come `query`, accanto a `data`. `builder.compress()` omette le chiavi del body il cui valore è `null` o `undefined`.

Example: Chiamare un'API
```js
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {
	console.log(err, response);
});
```

Example: Con una query
```js
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);
// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }
```

### builder.compress([value])

Type: `method`

Omette i valori vuoti dal body di una richiesta RESTBuilder.API().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean` | no | `true` | `false` lo disattiva. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Senza argomento o con `true`, il body JSON di una richiesta `RESTBuilder.API()` viene scritto senza le chiavi il cui valore è `null` o `undefined`, così la richiesta è più piccola. `compress(false)` lo disattiva. Gli altri builder non sono interessati.

Example: Body più piccolo
```js
RESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);
// data: { id: 'A1', total: 120 }
```

### RESTBuilder.upgrade(fn)

Type: `method`

Registra una funzione che modifica ogni builder prima che venga inviato.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(builder)`. |

La funzione viene eseguita per ogni builder dell'applicazione subito prima che venga effettuata la richiesta, con il builder come argomento. Usala per header o token condivisi. Gli upgrade non possono essere rimossi.

Example: Aggiungere un token a un servizio
```js
RESTBuilder.upgrade(function(builder) {
	if (builder.url().startsWith(CONF.shopapi))
		builder.header('X-Token', CONF.shoptoken);
});
```

### builder.url([url])

Type: `method`

Imposta o legge l'URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | Il nuovo URL. |

Returns: `RESTBuilder|String` Il builder, oppure l'URL quando viene chiamato senza argomento.

Con un argomento imposta l'URL e restituisce il builder; senza argomento restituisce l'URL corrente.

Example: Leggere l'URL
```js
var url = builder.url();
```

### builder.method(method, [data])

Type: `method`

Imposta il metodo HTTP.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `method` | `String` | yes |  | Il metodo HTTP. |
| `data` | `Object` | no |  | Dati inviati come JSON. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Imposta il metodo (le minuscole vengono convertite in maiuscole). `data` viene inviato come JSON.

Scorciatoie: `builder.get([query])` imposta `GET` e la query string; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` e `builder.delete([data])` impostano il metodo e il body (nel tipo impostato prima, JSON per impostazione predefinita); `builder.head()` imposta `HEAD`. I nomi in maiuscolo (`builder.POST()`) sono alias.

Example: Scorciatoie
```js
RESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);
```

### builder.json([data])

Type: `method`

Invia i dati come JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | I dati. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Imposta il tipo a JSON e il body a `data` (un oggetto viene serializzato quando la richiesta viene inviata). Una richiesta `GET` diventa `POST`.

Example: Body JSON
```js
RESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);
```

### builder.urlencoded([data])

Type: `method`

Invia i dati come form URL-encoded.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | I campi del form. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Imposta `Content-Type: application/x-www-form-urlencoded` e il body; un oggetto viene codificato quando la richiesta viene inviata. Una richiesta `GET` diventa `POST`.

Example: Form
```js
RESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);
```

### builder.xml([data])

Type: `method`

Invia un body XML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `String` | no |  | L'XML. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Imposta `Content-Type: text/xml` e il body. Passa l'XML come stringa. Una richiesta `GET` diventa `POST`.

Example: Body XML
```js
RESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);
```

### builder.raw(value, [type])

Type: `method`

Imposta il body così com'è.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Buffer` | yes |  | Il body. |
| `type` | `String` | no |  | Il tipo di contenuto breve. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Imposta il body senza alcuna serializzazione. `type` è uno dei tipi brevi di `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`); senza di esso imposta l'header con `builder.type()`. Una stringa viene inviata invariata. Un `Buffer` richiede il tipo `'raw'` (`application/octet-stream`); senza tipo viene serializzato come JSON come un oggetto.

Example: Body binario
```js
RESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);
```

### builder.text(value)

Type: `method`

Invia testo semplice e lascia la risposta non analizzata.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Il testo. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

`builder.plain(value)` è un alias. Imposta `Content-Type: text/plain` e il body, e la callback riceve il body grezzo della risposta invece di un valore analizzato.

Example: Testo semplice
```js
RESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {
	// response is the raw body
});
```

### builder.file(name, filename, [source])

Type: `method`

Aggiunge un file e invia una richiesta multipart.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del campo del form. |
| `filename` | `String` | yes |  | Il nome del file inviato al servizio. |
| `source` | `Buffer|String` | no |  | Un buffer, un percorso o un URL. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

La richiesta diventa `multipart/form-data` (una `GET` diventa `POST`). `source` è un `Buffer`, un percorso su disco o un URL che viene scaricato e trasmesso in streaming. Senza `source` il file viene letto da `filename`. Il body impostato con `json()` o `urlencoded()` viene inviato come campi aggiuntivi del form quando è un oggetto.

Example: Caricare due file
```js
RESTBuilder.POST('https://files.example.com/upload/')
	.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))
	.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')
	.callback(console.log);
```

### builder.header(name, value)

Type: `method`

Imposta un header della richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'header. |
| `value` | `String` | yes |  | Il valore. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Imposta un header. Helper per gli header comuni: `builder.referrer(url)` (alias `referer()`) imposta `Referer`, `builder.origin(url)` imposta `Origin`, `builder.csrf(token)` imposta `X-Csrf-Token` e `builder.xhr()` aggiunge `X-Requested-With: XMLHttpRequest`.

Example: Header
```js
builder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();
```

### builder.type(value)

Type: `method`

Imposta l'header Content-Type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Il tipo MIME. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Imposta `Content-Type` a un tipo MIME completo. Un tipo impostato da `json()`, `urlencoded()`, `xml()` o `text()` lo sostituisce, quindi usalo con `raw(value)`.

Example: Tipo personalizzato
```js
builder.raw('{"id":1}').type('application/vnd.api+json');
```

### builder.accept(ext)

Type: `method`

Imposta l'header Accept.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ext` | `String` | yes |  | Un'estensione o un tipo MIME. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Accetta un'estensione di file (`'json'`, `'xml'`, `'html'`...) e la converte nel suo tipo MIME; un valore più lungo viene usato così com'è.

Example: Accettare XML
```js
builder.accept('xml');
```

### builder.auth(user, [password])

Type: `method`

Imposta l'header Authorization.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `user` | `String` | yes |  | Il nome utente o l'intero valore dell'header. |
| `password` | `String` | no |  | La password. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Con `user` e `password` imposta l'autenticazione basic (`Basic base64(user:password)`). Con un solo argomento il valore viene usato così com'è, ad esempio `'Bearer TOKEN'`.

Example: Basic e Bearer
```js
builder.auth('admin', 'secret');
builder.auth('Bearer ' + CONF.apitoken);
```

### builder.cookie(name, value)

Type: `method`

Aggiunge un cookie alla richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del cookie. |
| `value` | `String` | yes |  | Il valore. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Aggiunge un cookie. `builder.cookies(obj)` sostituisce tutti i cookie con un oggetto `{ name: value }`.

Example: Cookie
```js
builder.cookie('session', token);
builder.cookies({ lang: 'en', theme: 'dark' });
```

### builder.cook([value])

Type: `method`

Conserva i cookie della risposta nel builder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean` | no | `true` | `false` lo disattiva. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Con `cook()` i cookie impostati dalla risposta vengono memorizzati nel builder e inviati con la richiesta successiva effettuata dallo stesso builder. `output.cookies` li contiene allora. `cook(false)` lo disattiva.

Example: Login, poi lettura
```js
RESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {
	RESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);
});
```

### builder.timeout(ms)

Type: `method`

Imposta il timeout.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ms` | `Number` | yes |  | Millisecondi. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Il timeout in millisecondi (10000 per impostazione predefinita). `0` lo disattiva. Quando scade l'errore è `408: Request Timeout`.

Example: Cinque secondi
```js
builder.timeout(5000);
```

### builder.keepalive([val])

Type: `method`

Riutilizza le connessioni con un agent keep-alive.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `val` | `Boolean` | no | `true` | Attiva o disattiva il keep-alive. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Senza argomento (o con un valore truthy) la richiesta usa l'agent keep-alive condiviso del framework, così le connessioni verso lo stesso host vengono riutilizzate. `keepalive(false)` lo disattiva. Non viene usato insieme a un proxy.

Example: Keep-alive
```js
RESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);
```

### builder.proxy(url)

Type: `method`

Invia la richiesta attraverso un proxy.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | Il proxy. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

`url` è `'host:port'` o `'http://host:port'`. Con `http://user:password@host:port` le credenziali vengono inviate come `Proxy-Authorization: Basic`. Le destinazioni HTTPS vengono incapsulate in un tunnel con `CONNECT`. Senza di esso viene usato il proxy della chiave di configurazione `$proxyrequest` quando è impostata.

Example: Proxy
```js
builder.proxy('http://10.0.0.5:3128');
```

Example: Proxy con login
```js
builder.proxy('http://user:secret@10.0.0.5:3128');
```

### builder.insecure()

Type: `method`

Accetta certificati TLS non validi.

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Accetta certificati autofirmati o scaduti del servizio. Usalo solo per servizi interni.

Example: Autofirmato
```js
RESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);
```

### builder.cert(key, cert, [dhparam])

Type: `method`

Imposta un certificato TLS del client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `Buffer` | yes |  | La chiave privata. |
| `cert` | `Buffer` | yes |  | Il certificato. |
| `dhparam` | `Buffer` | no |  | Parametri Diffie-Hellman. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Per i servizi che richiedono certificati client.

Example: Certificato client
```js
builder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));
```

### builder.unixsocket(socket, path)

Type: `method`

Invia la richiesta attraverso un socket Unix.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `socket` | `String` | yes |  | Il file del socket. |
| `path` | `String` | yes |  | Il percorso della richiesta, ad esempio `/api/`. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Si connette al file del socket invece che a un host; `path` è il percorso URL della richiesta.

Example: API di Docker
```js
RESTBuilder.make(function(builder) {
	builder.unixsocket('/var/run/docker.sock', '/containers/json');
	builder.callback(console.log);
});
```

### builder.nodnscache()

Type: `method`

Disattiva la cache DNS per questa richiesta.

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Per impostazione predefinita il builder risolve l'hostname una volta e mette in cache i suoi indirizzi. Con `nodnscache()` Node.js lo risolve a ogni richiesta.

Example: Senza cache DNS
```js
builder.nodnscache();
```

### builder.redirect(value)

Type: `method`

Attiva o disattiva il seguire dei redirect.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean` | yes |  | `false` smette di seguire i redirect. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

`redirect(false)` restituisce la risposta `301` o `302` stessa; leggi la destinazione in `output.headers.location`. Per impostazione predefinita vengono seguiti fino a quattro redirect.

Example: Leggere la location
```js
RESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {
	console.log(output.status, output.headers.location);
});
```

### builder.encrypt(key)

Type: `method`

Cifra il corpo e decifra la risposta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | La chiave di cifratura. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Il body viene cifrato con `key` e inviato con l'header `X-Encryption: a`; una risposta di testo viene decifrata con la stessa chiave. Entrambe le parti devono usare la stessa chiave.

Example: Chiamata cifrata
```js
builder.encrypt(CONF.sharedkey);
```

### builder.progress(fn)

Type: `method`

Riporta l'avanzamento del download.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(percentage)`. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Chiama `fn(percentage)` per ogni chunk ricevuto. La percentuale è nota solo quando la risposta ha `Content-Length`, altrimenti è `0`.

Example: Avanzamento
```js
builder.progress(function(percentage) {
	console.log(percentage.toFixed(1) + '%');
});
```

### builder.noparse()

Type: `method`

Restituisce il body grezzo della risposta.

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

La callback riceve il body come stringa (o un `Buffer` per i tipi binari) invece di un valore analizzato.

Example: HTML grezzo
```js
RESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {
	console.log(html.length);
});
```

### builder.base64()

Type: `method`

Restituisce il body della risposta in base64.

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

La callback riceve il body codificato in base64, ad esempio per incorporare un'immagine come data URI.

Example: Data URI
```js
RESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {
	var uri = 'data:image/png;base64,' + data;
});
```

### builder.debug()

Type: `method`

Stampa la richiesta e la risposta nella console.

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Dopo l'arrivo della risposta stampa lo stato, il metodo, l'URL con la query, l'errore e il body grezzo.

Example: Debug
```js
RESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);
```

### builder.callback([fn])

Type: `method`

Invia la richiesta e riceve la risposta analizzata.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|Object` | no |  | `function(err, response, output)` o il `$` di un'azione. |

Returns: `RESTBuilder|Promise` Il builder, oppure una promise quando viene chiamato senza argomento.

Invia la richiesta al tick successivo e passa il risultato a `fn(err, response, output)`:

- `response`: il body interpretato in base al suo `Content-Type` (JSON, anche per `text/plain`; URL-encoded; XML tramite il parser HTML; gli altri body vengono interpretati come JSON quando sembrano JSON). Un body vuoto produce un oggetto vuoto; una risposta `204` produce `true`.
- `output`: `status`, `headers`, `response` (il body grezzo), `hostname`, `origin`, `cookies` (con `cook()`) e `output.cookie(name)`, che legge un cookie della risposta.
- `err`: l'errore di rete o `'408: Request Timeout'`; un `ErrorBuilder` quando il body è un array di errori Total.js (`[{ error: '...' }]`, e allora `response` è `null`); altrimenti, per uno stato `400` o superiore, un `ErrorBuilder` con un errore il cui nome è il codice di stato e il cui messaggio è il body grezzo. Un valore impostato con `builder.error()` sostituisce qualsiasi errore.

`fn` può essere anche il `$` di un'azione: la risposta interpretata viene passata a `$.callback()` e un errore viene aggiunto agli errori di `$`. Senza argomento restituisce una promise che si risolve con `response` e viene rifiutata con `err`.

Example: Callback
```js
RESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {
	if (err)
		return console.log(err);
	console.log(output.status, response.length);
});
```

Example: In un'azione
```js
NEWACTION('Products/sync', {
	name: 'Sync products',
	action: function($) {
		RESTBuilder.GET(CONF.shopapi + '/products/').callback($);
	}
});
```

### builder.promise([$])

Type: `method`

Invia la richiesta e restituisce una promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | no |  | Il `$` di un'azione. |

Returns: `Promise` Si risolve con la risposta analizzata.

La promise si risolve con la risposta analizzata. In caso di errore viene rifiutata con un `Error` creato dall'errore (un `ErrorBuilder` diventa un `Error` con i suoi messaggi). Con `$` l'errore va invece a `$.invalid()` e la promise non viene rifiutata.

Example: await
```js
var user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();
```

Example: Con $
```js
var order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);
```

### builder.exec([callback])

Type: `method`

Invia subito la richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `function(err, response, output)`. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Invia la richiesta immediatamente e chiama `callback(err, response, output)` con gli stessi valori di `callback()`. Preferisci `callback()`, che attende il tick successivo. Quando `callback` è omessa il risultato viene ignorato.

Example: Exec
```js
RESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {
	console.log(err, response);
});
```

### builder.stream(callback)

Type: `method`

Restituisce la risposta come stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(err, response)`. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Invia la richiesta al tick successivo e chiama `callback(err, response)` non appena arrivano gli header. `response` ha `status`, `headers`, `origin` e `stream` (la risposta Node.js, non ancora letta). Usalo per i file di grandi dimensioni.

Example: Salvare un file di grandi dimensioni
```js
RESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {
	if (!err && response.status === 200)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));
});
```

### builder.error(value)

Type: `method` · Since: `0.0.16`

Sostituisce qualsiasi errore con un tuo valore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|String` | yes |  | L'errore da restituire, per esempio un messaggio o un `ErrorBuilder`. |

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Quando la richiesta termina con un errore qualsiasi (di rete, di timeout o uno stato `400` o superiore), la callback o la promise ricevono invece `value`. Usalo per nascondere ai tuoi utenti i dettagli di un servizio remoto.

Example: Errore personalizzato
```js
RESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);
```

### builder.logerror()

Type: `method` · Since: `0.0.16`

Stampa gli errori nella console.

Returns: `RESTBuilder` Lo stesso builder, per il concatenamento.

Quando la richiesta termina con un errore, l'errore (o il body grezzo della risposta) viene passato al gestore degli errori del framework, che lo stampa con il nome `RESTBuilder` e il metodo e l'URL della richiesta. La callback riceve comunque l'errore.

Example: Registrare gli errori
```js
RESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);
```
