Titanium HTTP request library inspired by node and python equivalents
Get the latest dist/request.js into your Resources folder or your app/lib folder, if you're using Alloy.
request.get(url, callback, [options])
request.post(url, callback, [options])
request.put(url, callback, [options])
request.delete(url, callback, [options])
request.get('http://www.example.com', function (err, res) {
if (res && res.json) console.log('Got JSON response:', res.json);
});
The response object is given as the second parameter of the callback, if no error occurred in the request.
- res.code: HTTP Status code
- res.text: Response as a String
- res.blob: Response in Titanium.Blob format
- res.xml: Response in Titanium.XML.Document format (null if res.text is not well-formed XML)
- res.json: Response as a JSON object (null if res.text is unparseable JSON)
- res.headers: Response headers as a JSON object
You can pass the following data through the options object argument:
- Request headers
- Query string
- Request body
The request headers are passed through options.headers using an object with the header names as its properties, and the header values as its values.
var headers = {
'cookie': 'session=E8vh78'
};
request.post('http://www.example.com/article', function (err, res) {
if (res && res.json) console.log('Got JSON response:', res.json);
}, {headers: headers});
The query string is passed through options.query using an object with the parameter names as its properties, and the parameter values as its values.
request.get('http://www.example.com/article/5', function (err, res) {
// this request will be called with the following URL:
// http://www.example.com/article/5?foo=bar&bar=baz
}, {query: {foo: 'bar', bar: 'baz'}});
The request body is passed through options.body using either a String, an Object or a Blob.
var payload = {
author: 'Mark Twain',
title: 'Tom Sawyer'
};
request.post('http://www.example.com/book', function (err, res) {
// payload was sent as a form-encoded POST data
}, {body: payload});
You can register a middleware if you want to execute some code
- before the request is sent
- before the response callback
Example 1: patch headers for all the requests
request.use(function (req, res) {
if (!!res) return; // If res is filled, the request has already been sent
req.headers['x-foo'] = 'bar';
});
Example 2: trigger event when user data is returned in the response
request.use(function (req, res) {
if (!!res && !!res.json && !!res.json.user) {
Ti.App.fireEvent('app:user:updated', {user: res.json.user});
}
});
By default cookies are not managed by request. You need to activate it by registering this middleware:
request.use(request.middlewares.cookie());
Requirements: ti_touchdb