---
title: Richieste HTTP
project: Total.js V4
version: 0.0.99
section: guides
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/http-requests/
updated: 2026-11-16T15:41:20.819Z
---

# Richieste HTTP

> Chiama altri servizi HTTP con RESTBuilder, REQUEST() e DOWNLOAD().

Total.js ha tre strumenti per chiamare altri servizi HTTP dalla tua applicazione:

- **`RESTBuilder`** costruisce una richiesta passo dopo passo, la invia e analizza la risposta (JSON, XML o URL-encoded). Usalo per le API REST.
- **`REQUEST(options, [callback])`** è il client HTTP di basso livello che `RESTBuilder` usa. Restituisce il corpo grezzo, oppure uno stream.
- **`DOWNLOAD(url, filename, [callback], [timeout])`** salva una risposta direttamente in un file.

Tutti e tre sono globali: puoi usarli in controller, schemi, definizioni e moduli senza `require()`.

## RESTBuilder

Un metodo statico crea il builder per il metodo HTTP che ti serve. I dati che passi a `POST`, `PUT`, `PATCH` e `DELETE` vengono inviati come JSON; i dati di `GET` diventano la query string.

```js
RESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {
	if (err) {
		console.log('Error:', err);
		return;
	}
	console.log(response);      // the parsed body
	console.log(output.status); // the HTTP status code
});

RESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {
	console.log(response);
});
```

La callback riceve tre argomenti:

| Argomento | Cosa contiene |
| --- | --- |
| `err` | Un errore, oppure `null` |
| `response` | Il corpo analizzato: un oggetto per le risposte JSON, XML e URL-encoded, altrimenti un oggetto vuoto |
| `output` | Dettagli: `value`, `response` (il corpo grezzo), `status`, `headers`, `hostname`, `origin`, `cache` e il metodo `cookie(name)` |

Un codice di stato `400` o superiore **non** è un errore per impostazione predefinita: controlla `output.status`, oppure chiama `strict()` per ottenere il codice di stato come `err`. Quando il servizio risponde con un array di errori Total.js (`[{ name, error }]`), `err` è un `ErrorBuilder` con quegli errori.

### Promise

`promise()` invia la richiesta e restituisce una promise del corpo analizzato. Passa `$` (le opzioni di un'operazione di schema) e l'errore va a `$.invalid()` invece di rifiutare la promise.

```js
NEWSCHEMA('Weather', function(schema) {
	schema.action('current', {
		name: 'Current weather',
		action: async function($) {
			var data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);
			$.callback(data);
		}
	});
});
```

Anche `callback()` senza una funzione restituisce una promise.

### Costruire la richiesta

Ogni metodo restituisce il builder, così puoi concatenarli. Non viene inviato nulla finché non chiami `callback()`, `exec()`, `promise()` o `stream()`.

```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/invoices/');
	builder.method('POST');
	builder.header('X-Token', CONF.token);
	builder.auth('user', 'password');
	builder.timeout(5000);
	builder.json({ number: '2024001', total: 120 });
	builder.callback(function(err, response, output) {
		console.log(output.status, response);
	});
});
```

| Ambito | Metodi |
| --- | --- |
| Indirizzo e metodo | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` |
| Intestazioni | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` |
| Corpo | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` |
| Cookie | `cookie()`, `cookies()`, `cook()` |
| Connessione | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` |
| Risposta | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` |
| Invio | `callback()`, `exec()`, `promise()`, `stream()` |

Il timeout predefinito è di 10 secondi. Il builder invia `User-Agent: Total.js/v...` e accetta JSON, testo e XML.

### Caricare file

`file()` aggiunge un file e fa passare la richiesta a `multipart/form-data` (un `GET` diventa un `POST`). Il contenuto può essere un percorso, un `Buffer` o un URL che il framework scarica e inoltra. `set()` aggiunge campi semplici del form.

```js
RESTBuilder.POST('https://api.example.com/upload/')
	.file('file', 'report.pdf', PATH.databases('report.pdf'))
	.set('folder', 'reports')
	.callback(function(err, response) {
		console.log(err, response);
	});
```

### Dare forma alla risposta

- `schema(name)` valida la risposta con uno schema e restituisce il modello. Qui un codice di stato `400` o superiore è un errore.
- `map('id:number,name:string')` mantiene solo i campi elencati e li converte; `id:number:itemid` rinomina anche `id` in `itemid`.
- `convert('price:number,date:date')` converte i campi della risposta con `CONVERT()`.
- `cache('5 minutes')` mette in cache in `F.cache` una risposta riuscita (`200`).

```js
RESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {
	// users === [{ id: 1, name: 'Peter' }, ...]
});
```

### Chiamare gli endpoint API di Total.js

`RESTBuilder.API(url, operation, [data])` invia un `POST` con il JSON `{ schema: operation, data: data }`, il formato delle route API di Total.js:

```js
RESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {
	console.log(response);
});
```

### Modifiche globali

`RESTBuilder.upgrade(fn)` esegue `fn(builder)` per ogni builder prima che invii la richiesta, per esempio per aggiungere un'intestazione a tutte le richieste. `RESTBuilder.addTransform(name, fn, [isDefault])` registra una funzione che modifica ogni risposta analizzata.

## REQUEST()

`REQUEST(options, [callback])` invia una singola richiesta HTTP. Il corpo che invii deve essere una stringa o un `Buffer`; il corpo della risposta è una stringa per i tipi di testo e `application/*`, altrimenti un `Buffer`. Senza callback restituisce una promise.

```js
REQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {
	if (err)
		return;
	console.log(response.status, response.headers, response.body);
});

var response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });
```

Con `custom: true` ottieni `response.stream` (il messaggio in arrivo) invece del corpo. Il framework segue i redirect `301` e `302` e copia i loro cookie nella richiesta successiva; `noredirect: true` lo disattiva.

## DOWNLOAD()

`DOWNLOAD(url, filename, [callback], [timeout])` scrive la risposta in un file. Un URL relativo (`/sitemap.xml`) viene richiesto alla tua stessa applicazione in esecuzione.

```js
DOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
	console.log(err, response.status);
});
```

## Proxy

`CONF.default_proxy` invia ogni richiesta attraverso un server proxy, tranne le richieste a `localhost`, `127.0.0.1` e `0.0.0.0`. `proxy(url)` e l'opzione `proxy` impostano un proxy per una singola richiesta. Il valore può contenere credenziali: `http://user:password@proxy.example.com:8080`.

La chiave di configurazione `default_restbuilder_timeout` (predefinito `10000`) è il timeout delle chiamate `REQUEST()` senza un proprio `timeout`.
