ForgeTotal.js 5
en

Total.js 5

Call another address with AJAX() from the server

Total.js 5 · total5@0.0.19 httprequestsajax Executed against Total.js 5

AJAX('METHOD url', [data], [callback]) makes an HTTP request and gives you the parsed answer. It is the short form of REQUEST() for APIs that talk JSON: the same call that jComponent has in the browser, so the code of the page and of the server look alike.

  • The address starts with an optional method: AJAX('POST [https://example.com/api/'](https://example.com/api/'), data). Without a method it is a GET.
  • data, when given, is sent as a JSON body. The request carries the header x-requested-with: XMLHttpRequest, so on the other side $.xhr is true.
  • The answer is parsed by its content type: JSON becomes an object, application/x-www-form-urlencoded becomes an object, anything else arrives as text.
  • When the status is 400 or more, the promise is rejected (or the callback gets the error first) with the parsed body of the answer as the error. A callback is called as callback(err, value, response).
  • Without a callback it returns a promise.

For XML answers use REQUEST() and parse the body yourself: AJAX() is made for JSON and text answers.

The example calls routes of the same application, whose address $.hostname('/') gives, so that it needs no other server.

controllers/calls.js
exports.install = function() {
	ROUTE('GET /api/hello/', hello);
	ROUTE('POST /api/echo/', echo);
	ROUTE('GET /api/text/', text);
	ROUTE('GET /api/xml/', xml);
	ROUTE('GET /api/fail/', fail);
	ROUTE('GET /calls/', calls);
};

function hello($) {
	$.json({ hello: 'world', xhr: $.xhr });
}

function echo($) {
	$.json({ received: $.body, xhr: $.xhr });
}

function text($) {
	$.plain('plain text');
}

function xml($) {
	$.xml('<a><b>1</b></a>');
}

function fail($) {
	$.invalid('It is wrong');
}

async function calls($) {

	const base = $.hostname('/');
	const out = {};

	out.hello = await AJAX('GET ' + base + 'api/hello/');
	out.nomethod = await AJAX(base + 'api/hello/');
	out.echo = await AJAX('POST ' + base + 'api/echo/', { a: 1 });
	out.text = await AJAX(base + 'api/text/');

	try {
		await AJAX(base + 'api/fail/');
	} catch (err) {
		out.error = err.message || err;
	}

	out.callback = await new Promise(resolve => AJAX(base + 'api/hello/', (err, value, response) => resolve({ err: err, hello: value.hello, status: response.status })));

	out.xml = await Promise.race([
		AJAX(base + 'api/xml/').then(() => 'answered', () => 'rejected'),
		new Promise(resolve => setTimeout(() => resolve('never answered'), 1000))
	]);

	$.json(out);
}