ForgeTotal.js 5
de

Total.js 5

Andere HTTP-APIs mit RESTBuilder aufrufen

Total.js 5 · total5@0.0.19 integrationshttprestbuilder Mit Total.js 5 ausgeführt

RESTBuilder.GET(url), .POST(url, data), .PUT, .PATCH und .DELETE bauen eine Anfrage. Die Daten eines POST werden als JSON gesendet. Verkette .header(name, value), .cookie(name, value), .timeout(milliseconds) und .auth(user, password) vor .exec(function(err, response, output) {}) (oder .promise() für await).

  • response ist der Body, automatisch geparst, wenn er JSON ist
  • output.status ist der HTTP-Status und output.headers sind die Response-Header
  • err ist bei Netzwerkfehlern und bei HTTP-Fehlerstatus gesetzt

Das Beispiel ruft zwei Routen der eigenen App auf, damit es überall laufen kann; verwende in deinem Code die Adresse des echten Dienstes. $.hostname(path) baut die vollständige URL dieses Servers.

controllers/service.js
exports.install = function() {
	ROUTE('GET /api/hello/', hello);
	ROUTE('POST /api/sum/', sum);
	ROUTE('GET /call/', call);
};

function hello($) {
	$.json({ message: 'hello', agent: $.headers['x-agent'] || null });
}

function sum($) {
	$.json({ sum: $.body.a + $.body.b });
}

async function call($) {

	var greeting = await RESTBuilder.GET($.hostname('/api/hello/')).header('x-agent', 'forge').timeout(5000).promise();
	var total = await RESTBuilder.POST($.hostname('/api/sum/'), { a: 20, b: 22 }).promise();

	RESTBuilder.GET($.hostname('/api/missing/')).exec(function(err, response, output) {
		$.json({ greeting: greeting, total: total, missing: output.status });
	});
}