Spanish Total.js
Italiano
Documentazione Per agenti IA
Indice

Controller

Proprietà e metodi del controller, l'oggetto che risponde a una richiesta.

.md GitHub
In questa pagina

Il controller è this dentro ogni azione di una route. Contiene i dati della richiesta e i metodi che rispondono alla richiesta. La guida Controller spiega come usarlo con esempi; questa pagina è il riferimento esatto.

API

property

controller.body

Il corpo della richiesta già analizzato.

Restituisce Object

Un corpo JSON o URL-encoded viene analizzato in un oggetto. I valori di un form sono stringhe. Una route con uno schema lo sostituisce con il modello validato. Puoi anche assegnare un nuovo oggetto.

Leggere il corpo
exports.install = function() {
	ROUTE('POST /api/contact/', contact);
};

function contact() {
	var email = this.body.email;
	this.success();
}
property

controller.query

La query string dell'URL come oggetto.

Restituisce Object

I valori sono stringhe: ?page=2 dà { page: '2' }. L'oggetto viene analizzato la prima volta che lo leggi.

Paginazione
function list() {
	var page = (this.query.page || '1').parseInt();
	this.json({ page: page });
}
property

controller.params

I parametri dinamici dell'URL.

Restituisce Object

Ogni {name} della route diventa una chiave. I parametri dichiarati con un tipo vengono convertiti: {id:number} con parseInt(), {active:boolean} con parseBoolean() e {date:date} con parseDate(). Gli stessi valori arrivano come argomenti dell'azione.

Parametro tipizzato
exports.install = function() {
	ROUTE('GET /orders/{id:number}/', order);
};

function order(id) {
	// this.params.id is a number
	this.json({ id: this.params.id });
}
property

controller.files

I file caricati.

Restituisce Array

Solo le route con il flag upload ricevono file. Ogni file ha name (il campo del form), filename, type, size, extension, width e height, e i metodi move(path), copy(path), read(), isImage(), isVideo() e isAudio(). move(), copy() e read() restituiscono una promise senza callback. I file temporanei vengono rimossi quando la richiesta termina, a meno che tu non chiami controller.autoclear(false).

Salvare un upload
exports.install = function() {
	ROUTE('POST /upload/', upload, ['upload'], 1024 * 5);
};

async function upload() {
	var file = this.files[0];
	await file.move(PATH.public('uploads/' + file.filename));
	this.success();
}
property

controller.user

L'utente autenticato.

Restituisce Object

L'oggetto che il tuo delegato AUTH() ha passato a $.success(user). È undefined quando nessuno è autenticato. Puoi assegnarlo.

Profilo
exports.install = function() {
	ROUTE('+GET /api/profile/', profile);
};

function profile() {
	this.json({ name: this.user.name });
}
property

controller.headers

Gli header della richiesta.

Restituisce Object

I nomi degli header sono in minuscolo.

Leggere un header
function api() {
	var token = this.headers['x-token'];
	this.plain(token ? 'ok' : 'missing');
}
property

controller.ip

L'indirizzo IP del client.

Restituisce String

Dietro un proxy è il primo indirizzo dell'header X-Forwarded-For; altrimenti l'indirizzo della connessione.

property

controller.url

Il percorso dell'URL della richiesta in minuscolo.

Restituisce String

Non ha query string e termina sempre con /.

property

controller.mobile

true quando il client è un dispositivo mobile.

Restituisce Boolean

Viene verificato sull'header User-Agent. Puoi assegnarlo.

property

controller.xhr

true quando la richiesta è stata inviata da XMLHttpRequest.

Restituisce Boolean

È true quando la richiesta ha l'header X-Requested-With: XMLHttpRequest.

property

controller.language

La lingua della richiesta.

Restituisce String

È il valore restituito dal tuo delegato di localizzazione (DEF.onLocale). Le viste e controller.mail() traducono i testi con essa.

property

controller.status

Il codice di stato HTTP della risposta.

Restituisce Number

Impostalo prima di rispondere. json(), jsonstring(), plain(), content() e html() lo usano, e usano 200 quando non è impostato. invalid() usa uno stato superiore a 399 per gli errori.

Creato
function create() {
	this.status = 201;
	this.json({ id: UID() });
}
property

controller.repository

Un oggetto condiviso dalla vista e dal suo layout.

Restituisce Object

I valori che salvi qui prima di view() sono disponibili nella vista e nel layout come repository. Vi vengono salvati anche il titolo della pagina e i meta tag.

Passare un valore al layout
function home() {
	this.repository.menu = 'home';
	this.view('index');
}
property

controller.exception

Il problema di una route di errore.

Restituisce Error|String

In una route per uno stato di errore (ROUTE('#404', ...), ROUTE('#500', ...)) contiene il problema passato a throw404(), throw500() e agli altri.

property

controller.req

L'oggetto richiesta del framework.

Restituisce Request

Estende la richiesta di Node.js. Le proprietà del controller come body, query e ip leggono da esso.

method

controller.json(obj, [headers], [beautify], [replacer])

Risponde con un oggetto serializzato come JSON.
ParametroTipoDescrizione
obj Object Il valore da serializzare.
headers? Object Header aggiuntivi della risposta.
beautify? Boolean Formatta il JSON con l'indentazione. Predefinito: false
replacer? Function Un replacer per JSON.stringify().

Restituisce Controller Il controller.

Il content type è application/json e lo stato è controller.status oppure 200. Un ErrorBuilder viene restituito come i suoi errori con il proprio stato. beautify può essere il secondo argomento.

Un oggetto
exports.install = function() {
	ROUTE('GET /api/products/', products);
};

function products() {
	this.json([{ id: 1, name: 'Book' }]);
}
Formattato
this.json({ name: 'Peter' }, true);
method

controller.jsonstring(str, [headers])

da 0.0.57 Risponde con un testo che è già JSON.
ParametroTipoDescrizione
str String Il testo JSON.
headers? Object Header aggiuntivi della risposta.

Restituisce Controller Il controller.

Usalo quando hai il JSON come stringa, per esempio da una cache. Il testo viene inviato così com'è, con il content type application/json.

Da una cache
function list() {
	this.jsonstring('[{"id":1}]');
}
method

controller.plain(body, [headers])

Risponde con testo semplice.
ParametroTipoDescrizione
body String|Object Il testo.
headers? Object Header aggiuntivi della risposta.

Restituisce Controller Il controller.

Il content type è text/plain. Un oggetto viene serializzato come JSON formattato; null dà un corpo vuoto.

Testo
function home() {
	this.plain('Hello world');
}
method

controller.html(body, [headers])

Risponde con HTML.
ParametroTipoDescrizione
body String L'HTML.
headers? Object Header aggiuntivi della risposta.

Restituisce Controller Il controller.

Equivale a content(body, 'text/html', headers).

HTML
function home() {
	this.html('<h1>Hello</h1>');
}
method

controller.content(body, type, [headers])

Risponde con un testo e il tuo content type.
ParametroTipoDescrizione
body String Il contenuto.
type? String Il content type. Predefinito: text/plain
headers? Object Header aggiuntivi della risposta.

Restituisce Controller Il controller.

Un ErrorBuilder come body viene restituito come JSON con il proprio stato.

XML
function feed() {
	this.content('<rss></rss>', 'application/xml');
}
method

controller.view([name], [model], [headers], [partial])

Renderizza una vista e risponde con essa.
ParametroTipoDescrizione
name? String Il nome della vista senza .html.
model? Object Il modello, disponibile nella vista come model.
headers? Object Header aggiuntivi della risposta.
partial? Boolean Restituisce l'HTML come stringa e non risponde. Può essere il terzo argomento. Predefinito: false

Restituisce Controller|String Il controller, oppure l'HTML quando partial è true.

La vista è un file name.html in views/, renderizzato dentro il layout (layout per impostazione predefinita, vedi controller.layout()). Le route di un controller diverso da default cercano le viste in views/<controller name>/. Il primo carattere del nome cambia il punto in cui viene cercato il file:

PrefissoDove
~La radice di views/
#plugin/viewLe viste di un plugin
=theme/viewLe viste di un tema
@Un pacchetto

Senza nome, la vista ha il nome dell'ultima parte dell'URL (index per /). Con partial impostato a true il metodo restituisce l'HTML renderizzato invece di rispondere.

Una pagina
exports.install = function() {
	ROUTE('GET /', home);
};

function home() {
	this.view('index', { title: 'Home' });
}
HTML come stringa
var html = this.view('~mail/order', order, true);
method

controller.layout(name)

Sceglie il layout per la vista successiva.
ParametroTipoDescrizione
name String Il nome della vista di layout, oppure una stringa vuota.

Restituisce Controller Il controller.

Il layout predefinito è layout (la configurazione default_layout). Una stringa vuota renderizza la vista senza layout.

Senza layout
function widget() {
	this.layout('');
	this.view('widget');
}
method

controller.title(value)

Imposta il titolo della pagina.
ParametroTipoDescrizione
value String Il titolo.

Restituisce Controller Il controller.

Il layout lo stampa con @{title}. Il testo viene codificato in HTML.

Titolo
this.title('Products');
this.view('products');
method

controller.meta(title, [description], [keywords], [image])

Imposta i valori meta della pagina.
ParametroTipoDescrizione
title String Il titolo.
description? String La descrizione.
keywords? String|Array Le parole chiave.
image? String L'URL di un'immagine.

Restituisce Controller Il controller.

Il layout li stampa con @{meta}. keywords può essere un array.

Meta tag
this.meta('Products', 'All our products', ['shop', 'books']);
this.view('products');
method

controller.file(filename, [download], [headers], [callback])

Risponde con un file.
ParametroTipoDescrizione
filename String Il file in public/, oppure ~ e un percorso assoluto.
download? String|Boolean Un nome per il file scaricato; true usa il nome del file.
headers? Object Header aggiuntivi della risposta.
callback? Function Viene eseguita quando il file è stato inviato.

Restituisce Controller Il controller.

Il file viene letto da public/. Un nome che inizia con ~ è un percorso assoluto.

Download
function invoice() {
	this.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');
}
method

controller.binary(buffer, type, [encoding], [download], [headers])

Risponde con un buffer.
ParametroTipoDescrizione
buffer Buffer I dati.
type String Il content type.
encoding? String Una conversione dei dati.
download? String Un nome per il file scaricato.
headers? Object Header aggiuntivi della risposta.

Restituisce Controller Il controller.

encoding converte il buffer prima dell'invio (binary, utf8, ascii).

Un'immagine in memoria
function pixel() {
	var buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');
	this.binary(buffer, 'image/gif');
}
method

controller.stream(stream, type, [download], [headers], [callback], [nocompress])

Risponde con uno stream leggibile.
ParametroTipoDescrizione
stream Stream Uno stream leggibile.
type String Il content type.
download? String Un nome per il file scaricato.
headers? Object Header aggiuntivi della risposta.
callback? Function Viene eseguita quando lo stream è stato inviato.
nocompress? Boolean Disattiva la compressione. Predefinito: false

Restituisce Controller Il controller.

La risposta viene compressa a meno che nocompress sia true. I primi due argomenti possono essere scambiati (type, stream).

Un file CSV
function exportcsv() {
	var stream = Fs.createReadStream(PATH.databases('export.csv'));
	this.stream(stream, 'text/csv', 'export.csv');
}
method

controller.redirect(url, [permanent])

Reindirizza il client a un altro URL.
ParametroTipoDescrizione
url String L'URL di destinazione.
permanent? Boolean Invia 301 Moved Permanently. Predefinito: false

Restituisce Controller Il controller.

Lo stato è 302, oppure 301 quando permanent è true.

Dopo un form
function save() {
	this.redirect('/thanks/');
}
method

controller.empty([headers])

Risponde con un corpo vuoto.
ParametroTipoDescrizione
headers? Object|Number Header aggiuntivi, oppure un codice di stato.

Restituisce Controller Il controller.

Un numero al posto degli header imposta il codice di stato. Per 204 No Content puoi usare anche controller.nocontent([headers]).

Accettato
this.empty(202);
method

controller.success([success], [value])

Risponde con il JSON { "success": true }.
ParametroTipoDescrizione
success? Boolean Il valore di success. Predefinito: true
value? Object Un valore aggiunto come value.

Restituisce Controller Il controller.

success(value) risponde { "success": true, "value": value }. success(false) risponde { "success": false }.

Con un valore
function create() {
	var id = UID();
	this.success(true, id);
	// {"success":true,"value":"..."}
}
method

controller.invalid([status], [error])

Risponde con un errore come JSON.
ParametroTipoDescrizione
status? Number|String|Error|ErrorBuilder Un codice di stato, il nome dell'errore o l'errore.
error? String Il testo dell'errore.

Restituisce ErrorBuilder Il builder con gli errori.

Gli errori vengono restituiti come array JSON con lo stato 400 (la configurazione default_errorbuilder_status). Un numero come primo argomento imposta lo stato; un Error o un ErrorBuilder viene restituito così com'è. La risposta viene inviata al tick successivo, quindi puoi ancora aggiungere errori al builder restituito.

Validazione
function save() {
	if (!this.body.email)
		return this.invalid('email', 'The email is required');
	this.success();
}
Un altro stato
this.invalid(409, 'The user exists');
method

controller.done([value])

Crea una callback che risponde con un successo o con un errore.
ParametroTipoDescrizione
value? Boolean|Object true aggiunge la risposta come value; un altro valore viene aggiunto esso stesso come value.

Restituisce Function Una callback (err, response).

La callback ha la forma (err, response). In caso di errore chiama controller.invalid(err). Altrimenti risponde { "success": true }; con done(true) la risposta viene aggiunta come value, e con un altro valore viene aggiunto quel valore.

Qualsiasi callback (err, response)
function remove(id) {
	// removeproduct(id, callback) is your own function
	removeproduct(id, this.done());
}

function create() {
	// answers { "success": true, "value": response }
	createproduct(this.body, this.done(true));
}
method

controller.callback([view])

Crea una callback che risponde con la risposta come JSON o con una vista.
ParametroTipoDescrizione
view? String Il nome di una vista.

Restituisce Function Una callback (err, data).

La callback ha la forma (err, data). Quando err è un ErrorBuilder e non hai passato una vista, i suoi errori vengono restituiti come JSON. Qualsiasi altro errore risponde con la pagina di errore 404, oppure 500 quando l'ErrorBuilder contiene un Error. Senza errori risponde con data come JSON, oppure renderizza la vista con data come modello.

JSON
function list() {
	// loadproducts(callback) is your own function
	loadproducts(this.callback());
}
Una vista
function list() {
	loadproducts(this.callback('products'));
}
method

controller.throw404([problem])

Risponde con la pagina di errore 404 Not Found.
ParametroTipoDescrizione
problem? String Una descrizione del problema, disponibile nella route di errore come controller.exception.

Restituisce Controller Il controller.

Esegue la route #404 quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. La stessa famiglia risponde ad altri stati: throw400(), throw401(), throw403(), throw409(), throw500(), throw501() e throw503(). Ognuno ha un alias chiamato view400() … view503(). Non succede nulla quando la richiesta ha già ricevuto risposta.

Record mancante
function detail(id) {
	var self = this;
	// findproduct(id, callback) is your own function
	findproduct(id, function(err, item) {
		if (item)
			self.view('detail', item);
		else
			self.throw404();
	});
}
La tua pagina
exports.install = function() {
	ROUTE('#404', notfound);
};

function notfound() {
	this.status = 404;
	this.view('404');
}
method

controller.throw403([problem])

Risponde con la pagina di errore 403 Forbidden.
ParametroTipoDescrizione
problem? String Una descrizione del problema, disponibile nella route di errore come controller.exception.

Restituisce Controller Il controller.

Esegue la route #403 quando ne hai dichiarata una. Alias: view403().

Solo per gli amministratori
function admin() {
	if (!this.user.admin)
		return this.throw403();
	this.view('admin');
}
method

controller.throw500([error])

Registra un errore nel log e risponde con la pagina di errore 500.
ParametroTipoDescrizione
error? Error|String L'errore.

Restituisce Controller Il controller.

L'errore viene registrato dal framework (DEF.onError). Poi viene eseguita la route #500 quando ne hai dichiarata una. Alias: view500().

In una promise
async function stats() {
	try {
		this.json(await loadstats());
	} catch (err) {
		this.throw500(err);
	}
}
method

controller.cookie(name, [value], [expires], [options])

Legge un cookie della richiesta o scrive un cookie nella risposta.
ParametroTipoDescrizione
name String Il nome del cookie.
value? String Il valore da scrivere.
expires? String Quando scade il cookie, per esempio '7 days'.
options? Object domain, path, secure, httponly, samesite.

Restituisce String|Controller Il valore in lettura, il controller in scrittura.

Con un solo argomento restituisce il valore del cookie, oppure una stringa vuota. Con un valore aggiunge un header Set-Cookie. expires è un testo come '5 days' o '2 hours'; uno negativo ('-1 day') rimuove il cookie. Al posto di expires puoi passare l'oggetto delle opzioni con expires al suo interno.

Opzioni: domain, path (predefinito /), secure (predefinito la configurazione default_cookies_secure), httponly e samesite (Lax, Strict o None; predefinito Lax, la configurazione default_cookies_samesite).

Scrivere e leggere
function login() {
	this.cookie('session', 'token', '7 days', { httponly: true });
	this.redirect('/');
}

function home() {
	var session = this.cookie('session');
	this.plain(session);
}
Rimuovere
this.cookie('session', '', '-1 day');
method

controller.header(name, value)

Imposta un header della risposta.
ParametroTipoDescrizione
name String Il nome dell'header.
value String Il valore.

Restituisce Controller Il controller.

Un header
this.header('X-Total', '42');
this.json(items);
method

controller.nocache()

Disattiva la cache HTTP della risposta.

Restituisce Controller Il controller.

Dati aggiornati
function stats() {
	this.nocache();
	this.json(getstats());
}
method

controller.csrf()

da 0.0.37 Crea un token CSRF per la richiesta corrente.

Restituisce String Il token.

Le route con il flag csrf verificano il token dall'header x-csrf-token o dall'argomento ?csrf= dell'URL. Nelle viste lo stesso token è @{csrf}.

Inviare il token
exports.install = function() {
	ROUTE('GET /api/token/', token);
	ROUTE('POST /api/save/ csrf', save);
};

function token() {
	this.json({ token: this.csrf() });
}
method

controller.autoclear([enable])

Conserva o rimuove i file caricati quando la richiesta termina.
ParametroTipoDescrizione
enable? Boolean false conserva i file. Predefinito: true

Restituisce Controller Il controller.

autoclear(false) conserva i file temporanei di controller.files dopo la risposta, per un lavoro che prosegue in seguito. controller.clear() li rimuove immediatamente.

Elaborare in seguito
function upload() {
	this.autoclear(false);
	var file = this.files[0];
	this.success();
	// file.path stays on the disk: process it, then remove it
}
method

controller.sse(data, [eventname], [id], [retry])

Invia un server-sent event.
ParametroTipoDescrizione
data String|Object I dati dell'evento.
eventname? String Il nome dell'evento.
id? String L'ID dell'evento.
retry? Number Quanto attende il browser prima di riconnettersi, in millisecondi.

Restituisce Boolean false quando l'evento non può essere inviato (il client si è disconnesso o la richiesta ha già ricevuto risposta).

La prima chiamata risponde con gli header di text/event-stream e mantiene aperta la connessione. Un oggetto viene serializzato come JSON. Quando manca retry, la prima chiamata usa il timeout della route. L'ID dell'evento precedente inviato dal browser si trova in controller.sseID. Lo stream termina con controller.close().

Un orologio
exports.install = function() {
	ROUTE('GET /clock/', clock, ['delay']);
};

function clock() {
	var self = this;
	var timer = setInterval(function() {
		if (!self.sse({ time: new Date() }))
			clearInterval(timer);
	}, 1000);
}
method

controller.proxy(options)

Inoltra la richiesta a un altro URL e risponde con la sua risposta.
ParametroTipoDescrizione
options Object|String L'URL di destinazione, oppure le opzioni.

Restituisce undefined Niente.

Il metodo, il corpo, la query string e gli header della richiesta vengono inviati alla destinazione (tranne host, connection, accept-encoding e gli header x-forwarded-*). Lo stato e il corpo della risposta vengono restituiti al client. In caso di errore chiama controller.invalid(err).

Opzioni: url (obbligatorio), method, headers, timeout (predefinito 10000 ms) e callback(err, response), che viene eseguita prima della risposta.

Inoltrare un'API
exports.install = function() {
	ROUTE('GET /api/weather/', weather);
};

function weather() {
	this.proxy('https://api.example.com/weather');
}
method

controller.baa([label])

Legge l'autenticazione Basic, oppure la chiede al browser.
ParametroTipoDescrizione
label? String Il realm mostrato dal browser.

Restituisce Object|null Le credenziali senza etichetta; null con un'etichetta.

Senza argomento restituisce { user, password, empty } dall'header Authorization. Con un'etichetta risponde 401 con l'header WWW-Authenticate, così il browser mostra una finestra di login.

Una pagina protetta
function admin() {
	var auth = this.baa();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.baa('Administration');
		return;
	}
	this.view('admin');
}
property

controller.isConnected

Indica se il client è ancora connesso.

Restituisce Boolean

È false dopo che il client ha chiuso la connessione o dopo controller.close(). Controllalo nei lavori lunghi prima di rispondere.

Lavoro lungo
function report() {
	var self = this;
	// longtask(callback) is your own function
	longtask(function(err, data) {
		if (self.isConnected)
			self.json(data);
	});
}
property

controller.isController

Sempre true per un controller.

Restituisce Boolean

Utile per distinguere un controller da un oggetto $ in una funzione condivisa.

Una funzione condivisa
function getuser(ctx) {
	return ctx.isController ? ctx.user : ctx.controller.user;
}
property

controller.secured

Indica se la richiesta è arrivata via HTTPS.

Restituisce Boolean

È true quando il protocollo è https: (o wss:). Dietro un proxy dipende dall'URL che vede il framework. Equivale a req.secured.

Forzare HTTPS
function index() {
	if (!this.secured)
		return this.redirect('https://' + this.req.host + this.url);
	this.view('index');
}
property

controller.referrer

L'header Referer della richiesta.

Restituisce String

Una stringa vuota quando l'header manca.

Tornare indietro
function back() {
	this.redirect(this.referrer || '/');
}
property

controller.robot

Indica se lo user agent sembra un bot.

Restituisce Boolean

Cerca nell'header User-Agent parole come bot, crawler e spider.

Esempio
function index() {
	if (this.robot)
		return this.plain('Hello robot');
	this.view('index');
}
property

controller.ua

Lo user agent analizzato, come testo breve con il browser e il sistema.

Restituisce String

Usa req.useragent(true) per ottenere un oggetto con il browser, il sistema operativo e il dispositivo. Equivale a req.ua.

Esempio
function index() {
	console.log(this.ua);
	this.view('index');
}
property

controller.uri

L'URL della richiesta già analizzato.

Restituisce Object

Un oggetto di url.parse() con pathname, query, hostname e le altre parti.

Esempio
function index() {
	this.plain(this.uri.pathname + ' ' + (this.uri.query || ''));
}
property

controller.split

Le parti del percorso dell'URL.

Restituisce String[]

/products/shoes/ dà ['products', 'shoes'].

Esempio
// GET /docs/{page}/
function docs() {
	this.plain(this.split.join(' > '));
}
property

controller.subdomain

Il sottodominio della richiesta come array.

Restituisce String[]

shop.eu.example.com dà ['shop', 'eu']; www viene ignorato. È null senza sottodominio.

Esempio
function index() {
	var tenant = this.subdomain ? this.subdomain[0] : 'default';
	this.view('index', { tenant: tenant });
}
property

controller.sessionid

L'id della sessione della richiesta.

Restituisce String

Impostato dal tuo delegato AUTH() o dal meccanismo delle sessioni. Equivale a req.sessionid.

Esempio
function logout() {
	// removesession(id) is your own function
	removesession(this.sessionid);
	this.redirect('/');
}
property

controller.sseID

L'id dell'ultimo evento ricevuto dal browser.

Restituisce String

Il valore dell'header Last-Event-ID che il browser invia quando si riconnette a una route di server-sent events, oppure null.

Esempio
function events() {
	var last = this.sseID;
	this.sse({ resumed: !!last });
}
property

controller.route

La route a cui corrisponde la richiesta.

Restituisce Object

Un oggetto interno del framework con l'URL, i flag, lo schema e le opzioni della route. Leggilo, non modificarlo.

Esempio
function index() {
	console.log(this.route.url);
	this.empty();
}
property

controller.options

Le opzioni personalizzate della route.

Restituisce Object

L'oggetto che passi a ROUTE() come opzioni.

Esempio
exports.install = function() {
	ROUTE('GET /reports/', report, { title: 'Reports' });
};

function report() {
	this.plain(this.options.title);
}
property

controller.flags

I flag della route.

Restituisce String[]

Un array con i flag della route, per esempio ['get', 'json'].

Esempio
function index() {
	this.json(this.flags);
}
property

controller.schema

Il nome dello schema della route.

Restituisce String

Per una route come POST /api/users/ *Users --> save è 'Users'. Una stringa vuota quando la route non ha uno schema.

Esempio
function action() {
	console.log(this.schema);
	this.empty();
}
property

controller.name

Il nome del controller.

Restituisce String

Il nome del file in /controllers/ (senza .js) che ha dichiarato la route.

Esempio
function index() {
	this.plain(this.name);
}
property

controller.breadcrumb

Il breadcrumb dell'elemento corrente della sitemap.

Restituisce Object[]

Gli elementi impostati da controller.sitemap(); nelle viste lo stesso elenco è in @{sitemap}.

Esempio
function detail() {
	this.sitemap('detail');
	this.json(this.breadcrumb);
}
method

controller.jsonp(name, obj, [headers], [beautify], [replacer])

Risponde con JSONP: una chiamata di una funzione JavaScript con i dati.
ParametroTipoDescrizione
name String Il nome della funzione JavaScript.
obj Object I dati.
headers? Object Header aggiuntivi della risposta.
beautify? Boolean Formatta il JSON. Predefinito: false
replacer? Function Un replacer per JSON.stringify().

Restituisce Controller Il controller.

Il corpo è name(json) con il content type application/x-javascript. Senza name la funzione è callback. Un ErrorBuilder viene restituito come i suoi errori.

Nome dalla query string
function data() {
	this.jsonp(this.query.callback, { count: 10 });
}
method

controller.throw400([problem])

Risponde con la pagina di errore 400 Bad Request.
ParametroTipoDescrizione
problem? String Una descrizione del problema.

Restituisce Controller Il controller.

Esegue la route #400 quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in controller.exception della route di errore. Alias: controller.view400().

Rispondere 400
function action() {
	this.throw400('Bad Request');
}
method

controller.throw401([problem])

Risponde con la pagina di errore 401 Unauthorized.
ParametroTipoDescrizione
problem? String Una descrizione del problema.

Restituisce Controller Il controller.

Esegue la route #401 quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in controller.exception della route di errore. Alias: controller.view401().

Rispondere 401
function action() {
	this.throw401('Unauthorized');
}
method

controller.throw409([problem])

Risponde con la pagina di errore 409 Conflict.
ParametroTipoDescrizione
problem? String Una descrizione del problema.

Restituisce Controller Il controller.

Esegue la route #409 quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in controller.exception della route di errore. Alias: controller.view409().

Rispondere 409
function action() {
	this.throw409('Conflict');
}
method

controller.throw501([problem])

Risponde con la pagina di errore 501 Not Implemented.
ParametroTipoDescrizione
problem? String Una descrizione del problema.

Restituisce Controller Il controller.

Esegue la route #501 quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in controller.exception della route di errore. Alias: controller.view501().

Rispondere 501
function action() {
	this.throw501('Not Implemented');
}
method

controller.throw503([problem])

Risponde con la pagina di errore 503 Service Unavailable.
ParametroTipoDescrizione
problem? String Una descrizione del problema.

Restituisce Controller Il controller.

Esegue la route #503 quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in controller.exception della route di errore. Alias: controller.view503().

Rispondere 503
function action() {
	this.throw503('Service Unavailable');
}
method

controller.view400([problem])

Alias di controller.throw400().
ParametroTipoDescrizione
problem? String Il problema.

Restituisce Controller Il controller.

Risponde con la pagina di errore 400 nello stesso modo.

Come throw400()
function detail() {
	this.view400();
}
method

controller.view401([problem])

Alias di controller.throw401().
ParametroTipoDescrizione
problem? String Il problema.

Restituisce Controller Il controller.

Risponde con la pagina di errore 401 nello stesso modo.

Come throw401()
function detail() {
	this.view401();
}
method

controller.view403([problem])

Alias di controller.throw403().
ParametroTipoDescrizione
problem? String Il problema.

Restituisce Controller Il controller.

Risponde con la pagina di errore 403 nello stesso modo.

Come throw403()
function detail() {
	this.view403();
}
method

controller.view404([problem])

Alias di controller.throw404().
ParametroTipoDescrizione
problem? String Il problema.

Restituisce Controller Il controller.

Risponde con la pagina di errore 404 nello stesso modo.

Come throw404()
function detail() {
	this.view404();
}
method

controller.view409([problem])

Alias di controller.throw409().
ParametroTipoDescrizione
problem? String Il problema.

Restituisce Controller Il controller.

Risponde con la pagina di errore 409 nello stesso modo.

Come throw409()
function detail() {
	this.view409();
}
method

controller.view500([error])

Alias di controller.throw500().
ParametroTipoDescrizione
error? Error L'errore, registrato nel log dal framework.

Restituisce Controller Il controller.

Risponde con la pagina di errore 500 nello stesso modo.

Come throw500()
function detail() {
	this.view500();
}
method

controller.view501([problem])

Alias di controller.throw501().
ParametroTipoDescrizione
problem? String Il problema.

Restituisce Controller Il controller.

Risponde con la pagina di errore 501 nello stesso modo.

Come throw501()
function detail() {
	this.view501();
}
method

controller.view503([problem])

Alias di controller.throw503().
ParametroTipoDescrizione
problem? String Il problema.

Restituisce Controller Il controller.

Risponde con la pagina di errore 503 nello stesso modo.

Come throw503()
function detail() {
	this.view503();
}
method

controller.nocontent([headers])

Risponde 204 No Content senza corpo.
ParametroTipoDescrizione
headers? Object Header aggiuntivi della risposta.

Restituisce Controller Il controller.

Niente da rispondere
function ping() {
	this.nocontent();
}
method

controller.destroy()

Chiude la connessione senza rispondere.

Restituisce Controller Il controller.

Il socket viene distrutto. Non succede nulla quando la richiesta ha già ricevuto risposta.

Scartare una richiesta
function upload() {
	if (this.req.headers['content-length'] > 1000000)
		return this.destroy();
	this.success();
}
method

controller.close([end])

Termina la risposta, soprattutto uno stream di server-sent events.
ParametroTipoDescrizione
end? Boolean Chiama res.end(). Predefinito: true

Restituisce Controller Il controller.

Termina la risposta di controller.sse() e contrassegna il controller come disconnesso. Con end impostato a false la risposta viene solo contrassegnata come terminata.

Fermare uno stream
function events() {
	var self = this;
	self.sse({ step: 1 });
	setTimeout(function() {
		self.close();
	}, 5000);
}
method

controller.cancel()

Contrassegna il controller come annullato.

Restituisce Controller Il controller.

Imposta controller.isCanceled a true. Chiamato in un handler di ON('controller'), impedisce l'esecuzione dell'azione della route, quindi l'handler deve rispondere da sé.

Fermare le richieste durante la manutenzione
ON('controller', function(controller) {
	if (CONF.maintenance) {
		controller.cancel();
		controller.throw503('Maintenance');
	}
});
method

controller.clear()

Rimuove subito i file caricati della richiesta.

Restituisce Controller Il controller.

I file temporanei di controller.files vengono eliminati e body, query e i cookie della richiesta vengono svuotati.

Dopo il lavoro
function upload() {
	var self = this;
	var file = self.files[0];
	file.move(PATH.databases(file.filename), function() {
		self.clear();
		self.success();
	});
}
method

controller.custom()

Ti permette di rispondere tu stesso con la risposta di Node.js.

Restituisce Boolean true quando puoi rispondere.

Il framework contrassegna la richiesta come già risposta e smette di attenderla. Poi scrivi su controller.res con writeHead() ed end(). Restituisce false quando la richiesta ha già ricevuto risposta.

Scrivere la risposta
function raw() {
	if (this.custom()) {
		this.res.writeHead(200, { 'Content-Type': 'text/plain' });
		this.res.end('OK');
	}
}
method

controller.error(err)

Registra nel log un errore con il nome del controller e l'URL.
ParametroTipoDescrizione
err Error|String L'errore.

Restituisce Controller Il controller.

L'errore va a F.error() e a controller.exception; alla richiesta non viene data risposta. Un ErrorBuilder invece viene restituito come JSON.

Registrare e continuare
function action() {
	this.error(new Error('Cache is empty'));
	this.json([]);
}
method

controller.successful(callback)

Crea una callback che risponde con l'errore e passa oltre solo il risultato.
ParametroTipoDescrizione
callback Function Viene eseguita in caso di successo con i risultati.

Restituisce Function Una callback (err, a, b, c).

La funzione restituita ha la forma (err, a, b, c). In caso di errore chiama controller.invalid(err); altrimenti chiama callback(a, b, c) con il controller come this.

Solo il percorso di successo
function detail(id) {
	NOSQL('products').one().where('id', id).callback(this.successful(function(item) {
		this.view('detail', item);
	}));
}
method

controller.hostname([path])

Crea un URL assoluto con l'host della richiesta.
ParametroTipoDescrizione
path? String Un percorso da aggiungere.

Restituisce String L'URL, per esempio https://example.com/products/.

Il protocollo, il nome host e la porta della richiesta, con path aggiunto.

Un link per un'email
function invite() {
	this.json({ url: this.hostname('/invite/' + UID() + '/') });
}
method

controller.image(filename, make, [headers], [callback])

Risponde con un'immagine modificata dall'elaboratore di immagini.
ParametroTipoDescrizione
filename String|Stream L'immagine.
make Function function(image).
headers? Object Header aggiuntivi della risposta.
callback? Function Viene eseguita quando la risposta termina.

Restituisce Controller Il controller.

filename è un file in /public/ (oppure un percorso completo preceduto da ~) o uno stream. make(image) modifica l'immagine con i metodi di Image (resize(), quality(), ...). Il risultato viene messo in cache in /tmp/. Richiede GraphicsMagick o ImageMagick.

Una miniatura
function thumbnail() {
	this.image('/img/photo.jpg', function(image) {
		image.resize(200, 200);
		image.quality(80);
	});
}
method

controller.memorize(key, expire, [disabled], fn, [fnFrom])

Mette in cache l'intera risposta di un'azione.
ParametroTipoDescrizione
key String La chiave nella cache.
expire String|Date Per quanto tempo, per esempio '5 minutes'.
disabled? Boolean true salta la cache. Predefinito: false
fn Function Crea la risposta; viene eseguita con il controller come this.
fnFrom? Function Viene eseguita prima di una risposta dalla cache.

Restituisce Controller Il controller.

La prima chiamata esegue fn e salva la risposta (una vista, JSON o testo) sotto key per expire. Le chiamate successive rispondono dalla cache, e prima viene eseguita fnFrom. Con disabled impostato a true la cache viene saltata. Il tema viene aggiunto alla chiave.

Mettere in cache la home page
function index() {
	this.memorize('home', '5 minutes', DEBUG, function() {
		this.view('index');
	});
}
method

controller.description(value)

Imposta la meta description della pagina.
ParametroTipoDescrizione
value String La descrizione.

Restituisce Controller Il controller.

Nel layout viene scritta da @{meta}. controller.keywords() imposta le parole chiave e controller.author() l'autore nello stesso modo.

Meta tag
function index() {
	this.title('Shop');
	this.description('Shoes and clothes');
	this.view('index');
}
method

controller.keywords(value)

Imposta le meta keywords della pagina.
ParametroTipoDescrizione
value String|Array Le parole chiave.

Restituisce Controller Il controller.

Un array viene unito con virgole. Nel layout vengono scritte da @{meta}.

Parole chiave
function index() {
	this.keywords(['shoes', 'clothes']);
	this.view('index');
}
method

controller.head([value], [...])

Aggiunge tag nell'head del layout, oppure li legge.
ParametroTipoDescrizione
value? String Il nome di un file o un tag HTML.

Restituisce Controller|String Il controller, oppure l'HTML senza argomenti.

Un file .css diventa un <link> e un file .js uno <script>; i nomi relativi puntano a /public/css/ e /public/js/. Un valore che inizia con < viene aggiunto così com'è. Ogni valore viene aggiunto una sola volta. Senza argomenti restituisce l'HTML; nel layout usa @{head}.

File per una pagina
function editor() {
	this.head('editor.css', 'editor.js');
	this.view('editor');
}
method

controller.place(name, [value], [...])

Aggiunge contenuto in un punto con nome del layout, oppure lo legge.
ParametroTipoDescrizione
name String Il nome del punto.
value? String Il contenuto.

Restituisce Controller|String Il controller, oppure il contenuto con solo name.

Un valore .js diventa uno <script> e un valore .css un <link>; gli altri valori vengono aggiunti così come sono. Nel layout usa @{place('name')}.

Script alla fine della pagina
function index() {
	this.place('footer', '/js/chart.js');
	this.view('index');
}
method

controller.theme(name)

Imposta il tema delle viste di questa richiesta.
ParametroTipoDescrizione
name String Il nome del tema.

Restituisce Controller Il controller.

Viste, layout e file statici vengono quindi cercati prima in /themes/{name}/. Il valore predefinito proviene da CONF.default_theme.

Un tema per cliente
function index() {
	this.theme(this.query.dark ? 'dark' : 'default');
	this.view('index');
}
method

controller.component(name, [settings], [model])

Renderizza un componente in HTML.
ParametroTipoDescrizione
name String Il nome del componente.
settings? Object Le impostazioni del componente.
model? Object Il modello; per impostazione predefinita il modello della vista.

Restituisce String L'HTML, oppure una stringa vuota per un componente sconosciuto.

Il componente è un file in /components/. Il suo CSS e il suo JS vengono aggiunti all'head del layout. Nelle viste usa @{component('name')}.

HTML di un componente
function widget() {
	this.html(this.component('chart', { color: 'red' }));
}
method

controller.helper(name, [arg], [...])

Esegue un helper di vista da DEF.helpers.
ParametroTipoDescrizione
name String Il nome dell'helper.
arg? Object Argomenti per l'helper.

Restituisce String L'output dell'helper.

L'helper viene eseguito con il controller come this. Un helper sconosciuto restituisce una stringa vuota.

Usare un helper in un'azione
DEF.helpers.price = function(value) {
	return value.format(2) + ' EUR';
};

function price() {
	this.plain(this.helper('price', 10));
}
method

controller.public(name, [path])

Crea l'URL di un file in /public/.
ParametroTipoDescrizione
name String Il file.
path? String Un percorso unito a un URL relativo.

Restituisce String L'URL.

Rispetta le impostazioni degli URL statici e il tema. La famiglia controller.public_js(), public_css(), public_image(), public_video(), public_font() e public_download() fa lo stesso per la propria cartella.

Un URL in JSON
function config() {
	this.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });
}
method

controller.public_js(name, [tag])

Crea l'URL di un file nella cartella pubblica js.
ParametroTipoDescrizione
name String Il file.
tag? Boolean Restituisce un tag HTML. Predefinito: false

Restituisce String L'URL.

La cartella proviene dalla configurazione (static_url_script, predefinito /js/). Con tag impostato a true restituisce il tag HTML (<script> o <link>).

URL di un file
function index() {
	this.plain(this.public_js('app.js'));
}
method

controller.public_css(name, [tag])

Crea l'URL di un file nella cartella pubblica css.
ParametroTipoDescrizione
name String Il file.
tag? Boolean Restituisce un tag HTML. Predefinito: false

Restituisce String L'URL.

La cartella proviene dalla configurazione (static_url_style, predefinito /css/). Con tag impostato a true restituisce il tag HTML (<script> o <link>).

URL di un file
function index() {
	this.plain(this.public_css('app.css'));
}
method

controller.public_image(name)

Crea l'URL di un file nella cartella pubblica img.
ParametroTipoDescrizione
name String Il file.

Restituisce String L'URL.

La cartella proviene dalla configurazione (static_url_image, predefinito /img/).

URL di un file
function index() {
	this.plain(this.public_image('logo.png'));
}
method

controller.public_video(name)

Crea l'URL di un file nella cartella pubblica videos.
ParametroTipoDescrizione
name String Il file.

Restituisce String L'URL.

La cartella proviene dalla configurazione (static_url_video, predefinito /videos/).

URL di un file
function index() {
	this.plain(this.public_video('intro.mp4'));
}
method

controller.public_font(name)

Crea l'URL di un file nella cartella pubblica fonts.
ParametroTipoDescrizione
name String Il file.

Restituisce String L'URL.

La cartella proviene dalla configurazione (static_url_font, predefinito /fonts/).

URL di un file
function index() {
	this.plain(this.public_font('icons.woff2'));
}
method

controller.public_download(name)

Crea l'URL di un file nella cartella pubblica download.
ParametroTipoDescrizione
name String Il file.

Restituisce String L'URL.

La cartella proviene dalla configurazione (static_url_download, predefinito /download/).

URL di un file
function index() {
	this.plain(this.public_download('manual.pdf'));
}
method

controller.runtest(url, [name], [callback])

Aggiunge un test di una route ai test del framework.
ParametroTipoDescrizione
url String La route da testare.
name? String Il nome del test.
callback? Function function(result) che restituisce true in caso di successo.

Restituisce Object Il test.

I test di un controller vengono eseguiti uno dopo l'altro. url è una route come 'GET /api/products/' o 'API /api/ products_query' (in quel caso il nome del test è l'operazione). callback(result) riceve { err, value, response, name } e restituisce true quando il test passa; senza di essa, un test passa quando non c'è errore.

Testare le route da una route
function selftest() {
	this.runtest('GET /api/products/', function(result) {
		return !result.err && result.value instanceof Array;
	});
	this.success();
}
property

req.host

L'header Host della richiesta.

Restituisce String

Il nome host con la porta, per esempio example.com:8000.

Esempio
function index() {
	this.plain(this.req.host);
}
property

req.secured

Indica se la richiesta è arrivata via HTTPS.

Restituisce Boolean

È true quando il protocollo è https: o wss:.

Esempio
MIDDLEWARE('https', function($) {
	if ($.req.secured)
		$.next();
	else
		$.res.redirect('https://' + $.req.host + $.req.url);
});
property

req.isAuthorized

Il risultato dell'autorizzazione.

Restituisce Boolean

È true finché il tuo delegato AUTH() non viene eseguito; poi è true quando il delegato ha accettato l'utente e false quando lo ha rifiutato.

Esempio
function index() {
	this.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');
}
property

req.isStaticFile

Indica se la richiesta chiede un file statico.

Restituisce Boolean

È true quando l'URL ha un'estensione di file e i file statici sono consentiti. Utile in DEF.onLocale e nei middleware.

Esempio
DEF.onLocale = function(req) {
	return req.isStaticFile ? '' : (req.query.lang || 'en');
};
property

req.xhr

Indica se la richiesta è arrivata da JavaScript.

Restituisce Boolean

È true quando l'header X-Requested-With è XMLHttpRequest.

Esempio
function index() {
	if (this.req.xhr)
		this.json({ ok: true });
	else
		this.view('index');
}
property

req.ip

L'indirizzo IP del client.

Restituisce String

Dietro un proxy è il primo indirizzo di X-Forwarded-For. Può essere impostato.

Esempio
function index() {
	this.plain(this.req.ip);
}
property

req.uri

L'URL della richiesta già analizzato.

Restituisce Object

Un oggetto di url.parse() con pathname, query, hostname e port.

Esempio
function index() {
	this.plain(this.req.uri.pathname);
}
property

req.path

Le parti del percorso in minuscolo.

Restituisce String[]

/Products/Shoes/ dà ['products', 'shoes']. req.split mantiene le maiuscole e minuscole originali.

Esempio
function index() {
	this.json(this.req.path);
}
property

req.split

Le parti del percorso dell'URL.

Restituisce String[]

Le parti così come erano nell'URL. Equivale a controller.split.

Esempio
function index() {
	this.json(this.req.split);
}
property

req.subdomain

Il sottodominio come array, oppure null.

Restituisce String[]

www viene ignorato. a.localhost dà ['a'].

Esempio
function index() {
	this.json(this.req.subdomain);
}
property

req.mobile

Indica se lo user agent è un dispositivo mobile.

Restituisce Boolean

Verifica l'header User-Agent. Può essere impostato.

Esempio
function index() {
	this.view(this.req.mobile ? 'mobile' : 'index');
}
property

req.robot

Indica se lo user agent sembra un bot.

Restituisce Boolean

Verifica l'header User-Agent.

Esempio
function index() {
	this.plain(this.req.robot ? 'bot' : 'human');
}
property

req.ua

Lo user agent analizzato, come testo breve con il browser e il sistema.

Restituisce String

Equivale a req.useragent().

Esempio
function index() {
	this.plain(this.req.ua);
}
property

req.query

La query string come oggetto.

Restituisce Object

Viene analizzata alla prima lettura e può essere impostata.

Esempio
function index() {
	this.json(this.req.query);
}
property

req.body

Il corpo della richiesta già analizzato.

Restituisce Object

Un corpo JSON o di un form. Equivale a controller.body.

Esempio
function save() {
	this.json(this.req.body);
}
property

req.files

I file caricati.

Restituisce HttpFile[]

Un array di oggetti HttpFile per le route con il flag upload. Equivale a controller.files.

Esempio
function upload() {
	this.json(this.req.files.map(function(file) {
		return file.filename;
	}));
}
property

req.user

L'utente accettato dal delegato AUTH(), oppure null.

Restituisce Object

Equivale a controller.user.

Esempio
function index() {
	this.json(this.req.user);
}
property

req.session

L'oggetto sessione della richiesta, oppure null.

Restituisce Object

Impostato dal tuo delegato AUTH() o dal meccanismo delle sessioni. Equivale a controller.session.

Esempio
function index() {
	this.json(this.req.session);
}
method

req.useragent([structured])

Analizza l'header User-Agent.
ParametroTipoDescrizione
structured? Boolean Restituisce un oggetto. Predefinito: false

Restituisce String|Object Lo user agent.

Senza argomento restituisce un testo breve con i nomi trovati nell'header, come il browser e il sistema. Con true restituisce { os, browser, device }, dove device è desktop, mobile, tablet o tv. Il risultato viene messo in cache sulla richiesta.

Dettagli del dispositivo
function index() {
	this.json(this.req.useragent(true));
}
method

req.cookie(name)

Legge un cookie della richiesta.
ParametroTipoDescrizione
name String Il nome del cookie.

Restituisce String Il valore.

Il valore viene decodificato. Un cookie mancante dà una stringa vuota. controller.cookie(name) fa lo stesso.

Leggere un cookie in un middleware
MIDDLEWARE('lang', function($) {
	$.req.$language = $.req.cookie('lang') || 'en';
	$.next();
});
method

req.authorization()

Legge l'header di autorizzazione Basic.

Restituisce Object { user, password, empty }.

Decodifica Authorization: Basic ... in { user, password, empty }. empty è true quando manca l'utente o la password.

Autenticazione Basic
function admin() {
	var auth = this.req.authorization();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.header('WWW-Authenticate', 'Basic realm="Admin"');
		return this.throw401();
	}
	this.view('admin');
}
method

req.authorize(callback)

Esegue manualmente il delegato AUTH() per questa richiesta.
ParametroTipoDescrizione
callback Function function(err, user, isAuthorized).

Restituisce Request La richiesta.

callback(err, user, isAuthorized) riceve il risultato del delegato. Senza delegato isAuthorized è false. Utile per le route che non usano i flag di autorizzazione.

Verificare un utente su una route pubblica
function index() {
	var self = this;
	self.req.authorize(function(err, user, isAuthorized) {
		self.view('index', { user: isAuthorized ? user : null });
	});
}
method

req.clear()

Rimuove i file caricati della richiesta.

Restituisce Request La richiesta.

Equivale a controller.clear().

Svuotare i file
function upload() {
	this.req.clear();
	this.success();
}
method

req.csrf()

da 0.0.37 Crea un token CSRF per la richiesta.

Restituisce String Il token.

Equivale a controller.csrf(); usa DEF.onCSRFcreate(req).

Un token in un middleware
MIDDLEWARE('token', function($) {
	$.res.setHeader('X-CSRF-Token', $.req.csrf());
	$.next();
});
method

req.encrypt([enable])

Cifra la risposta testuale di questa richiesta.
ParametroTipoDescrizione
enable? Boolean false la disattiva. Predefinito: true

Restituisce Request La richiesta.

La risposta viene cifrata con CONF.secret_encryption e riceve l'header X-Encryption: a. controller.encrypt([enable]) fa lo stesso.

Cifrare una risposta
function secret() {
	this.req.encrypt();
	this.json({ token: UID() });
}
method

req.hostname([path])

Crea un URL assoluto con l'host della richiesta.
ParametroTipoDescrizione
path? String Un percorso da aggiungere.

Restituisce String L'URL.

Il protocollo, il nome host e la porta della richiesta, con path aggiunto. Equivale a controller.hostname().

URL assoluto
function index() {
	this.plain(this.req.hostname('/login/'));
}
method

req.nocache()

Disattiva la cache HTTP della risposta.

Restituisce Request La richiesta.

Chiama res.nocache().

In un middleware
MIDDLEWARE('nocache', function($) {
	$.req.nocache();
	$.next();
});
property

res.controller

Il controller della richiesta.

Restituisce Controller

Impostato quando un controller gestisce la richiesta.

Esempio
MIDDLEWARE('log', function($) {
	console.log($.res.controller ? 'controller' : 'no controller');
	$.next();
});
property

res.success

Indica se la risposta è stata inviata.

Restituisce Boolean

È true dopo che il framework ha risposto alla richiesta.

Esempio
function action() {
	var self = this;
	setTimeout(function() {
		if (!self.res.success)
			self.empty();
	}, 1000);
}
property

res.nocompress

Disattiva la compressione dell'HTML e dei file statici per questa risposta.

Restituisce Boolean

Con true il framework non minifica l'HTML e i file statici che invia.

Esempio
MIDDLEWARE('raw', function($) {
	$.res.nocompress = true;
	$.next();
});
method

res.json(obj)

Risponde con un oggetto come JSON.
ParametroTipoDescrizione
obj Object Il valore.

Restituisce Response La risposta.

Lo stato proviene dalle opzioni della risposta (200 per impostazione predefinita).

JSON da una route con (req, res)
ROUTE('GET /api/ping/', function(req, res) {
	res.json({ ok: true });
});
method

res.content(code, body, type, [compress], [headers])

Risponde con un corpo e un content type.
ParametroTipoDescrizione
code Number Lo stato HTTP.
body String Il corpo.
type String Il content type.
compress? Boolean Compressione.
headers? Object Header aggiuntivi della risposta.

Restituisce Response La risposta.

I corpi oltre 4 kB vengono compressi con GZIP.

Un CSV
ROUTE('GET /export/', function(req, res) {
	res.content(200, 'id;name\n1;Peter', 'text/csv');
});
method

res.send([code], body, [type])

Risponde nello stile di Express.
ParametroTipoDescrizione
code? Number Lo stato HTTP. Predefinito: 200
body String|Object|Number Il corpo.
type? String Il content type.

Restituisce Response La risposta.

Una stringa è text/html, un numero viene restituito come il testo di quello stato, un oggetto è JSON e un ErrorBuilder viene restituito come i suoi errori. È pensato per i middleware scritti per Express.

Stile Express
ROUTE('GET /hello/', function(req, res) {
	res.send('<b>Hello</b>');
});
method

res.binary(buffer, type, [encoding], [download], [headers])

Risponde con un buffer.
ParametroTipoDescrizione
buffer Buffer I dati.
type String Il content type.
encoding? String La codifica del buffer.
download? String Un nome di file da scaricare.
headers? Object Header aggiuntivi della risposta.

Restituisce Response La risposta.

download imposta il nome del file di Content-Disposition.

Un file generato
ROUTE('GET /file/', function(req, res) {
	res.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');
});
method

res.image_nocache(input, make, [headers], [callback])

Risponde con un'immagine modificata senza la cache di /tmp/.
ParametroTipoDescrizione
input String|Stream L'immagine.
make Function function(image).
headers? Object Header aggiuntivi della risposta.
callback? Function Viene eseguita alla fine.

Restituisce Response La risposta.

Funziona come res.image(), ma il risultato viene creato per ogni richiesta.

Immagine con un timestamp
ROUTE('GET /stamp/', function(req, res) {
	res.image_nocache(PATH.public('img/photo.jpg'), function(image) {
		image.resize(300, 200);
	});
});
method

res.nocache()

Disattiva la cache HTTP della risposta.

Restituisce Response La risposta.

Rimuove If-None-Match e If-Modified-Since dalla richiesta e imposta Cache-Control: private, no-cache, no-store, max-age=0.

In una route con (req, res)
ROUTE('GET /now/', function(req, res) {
	res.nocache();
	res.json({ now: new Date() });
});
method

res.throw409([problem])

Risponde con la pagina di errore 409 Conflict.
ParametroTipoDescrizione
problem? String Una descrizione del problema.

Restituisce Response La risposta.

Esegue la route #409 quando ne hai dichiarata una.

Rispondere 409
ROUTE('GET /legacy/', function(req, res) {
	res.throw409();
});
method

res.throw501([problem])

Risponde con la pagina di errore 501 Not Implemented.
ParametroTipoDescrizione
problem? String Una descrizione del problema.

Restituisce Response La risposta.

Esegue la route #501 quando ne hai dichiarata una.

Rispondere 501
ROUTE('GET /legacy/', function(req, res) {
	res.throw501();
});
Fatto in Europa