From 0d8d7735d9e22bf1377a5fd960a0bf64cef87d6f Mon Sep 17 00:00:00 2001 From: Sefa Ilkimen Date: Fri, 27 Oct 2017 12:16:01 +0200 Subject: [PATCH] - improve docu for "setHeader" method - add test case for "setHeader" call with port number --- CHANGELOG.md | 2 +- README.md | 215 +++++++++++++++++++++++++---------------- test/js-mocha-specs.js | 21 +++- 3 files changed, 152 insertions(+), 86 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc038ae..0f97b79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## v1.7.1 - Fixed #36: setting basic authentication not working correctly -- Fixed #35: Android headers not normalized (not returned in lowercase) +- Fixed #35: Android headers are not normalized (not returned in lowercase) ## v1.7.0 diff --git a/README.md b/README.md index 4943a51..a4ac71e 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,11 @@ Please check [CHANGELOG.md](CHANGELOG.md) for details about updating to a new ve The plugin conforms to the Cordova plugin specification, it can be installed using the Cordova / Phonegap command line interface. - phonegap plugin add cordova-plugin-advanced-http +```shell +phonegap plugin add cordova-plugin-advanced-http - cordova plugin add cordova-plugin-advanced-http +cordova plugin add cordova-plugin-advanced-http +``` ## Usage @@ -38,7 +40,9 @@ This plugin registers a global object located at `cordova.plugin.http`. This plugin creates a cordovaHTTP service inside of a cordovaHTTP module. You must load the module when you create your app's module. - var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'cordovaHTTP']); +```js +var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'cordovaHTTP']); +``` You can then inject the cordovaHTTP service into your controllers. The functions can then be used identically to the examples shown below except that instead of accepting success and failure callback functions, each function returns a promise. For more information on promises in AngularJS read the [AngularJS docs](http://docs.angularjs.org/api/ng/service/$q). For more info on promises in general check out this article on [html5rocks](http://www.html5rocks.com/en/tutorials/es6/promises/). Make sure that you load cordova.js or phonegap.js after AngularJS is loaded. @@ -48,32 +52,54 @@ You can then inject the cordovaHTTP service into your controllers. The function ### getBasicAuthHeader This returns an object representing a basic HTTP Authorization header of the form `{'Authorization': 'Basic base64encodedusernameandpassword'}` - var header = cordova.plugin.http.getBasicAuthHeader("user", "password"); +```js +var header = cordova.plugin.http.getBasicAuthHeader('user', 'password'); +``` ### useBasicAuth This sets up all future requests to use Basic HTTP authentication with the given username and password. - cordova.plugin.http.useBasicAuth("user", "password"); +```js +cordova.plugin.http.useBasicAuth('user', 'password'); +``` ### setHeader Set a header for all future requests to a specified host. Takes a hostname, a header and a value. - cordova.plugin.http.setHeader("Hostname", "Header", "Value"); +```js +cordova.plugin.http.setHeader('Hostname', 'Header', 'Value'); +``` You can also define headers used for all hosts by using wildcard character "\*" or providing only two params. - cordova.plugin.http.setHeader("\*", "Header", "Value"); - cordova.plugin.http.setHeader("Header", "Value"); +```js +cordova.plugin.http.setHeader('*', 'Header', 'Value'); +cordova.plugin.http.setHeader('Header', 'Value'); +``` + +The hostname also includes the port number. If you define a header for `www.example.com` it will not match following URL `http://www.example.com:8080`. + +```js +// will match http://www.example.com/... +cordova.plugin.http.setHeader('www.example.com', 'Header', 'Value'); + +// will match http://www.example.com:8080/... +cordova.plugin.http.setHeader('www.example.com:8080', 'Header', 'Value'); +``` ### disableRedirect If set to `true`, it won't follow redirects automatically. This is a global setting. - cordova.plugin.http.disableRedirect(true); +```js +cordova.plugin.http.disableRedirect(true); +``` ### setDataSerializer Set the data serializer which will be used for all future PATCH, POST and PUT requests. Takes a string representing the name of the serializer. - cordova.plugin.http.setDataSerializer("urlencoded"); +```js +cordova.plugin.http.setDataSerializer('urlencoded'); +``` You can choose one of these two: * `urlencoded`: send data as url encoded content in body (content type "application/x-www-form-urlencoded") @@ -84,12 +110,16 @@ Caution: `urlencoded` does not support serializing deep structures whereas `json ### setRequestTimeout Set how long to wait for a request to respond, in seconds. - cordova.plugin.http.setRequestTimeout(5.0); +```js +cordova.plugin.http.setRequestTimeout(5.0); +``` ### clearCookies Clear the cookie store. - cordova.plugin.http.clearCookies(); +```js +cordova.plugin.http.clearCookies(); +``` ## Asynchronous Functions These functions all take success and error callbacks as their last 2 arguments. @@ -101,20 +131,24 @@ To use SSL pinning you must include at least one .cer SSL certificate in your ap As an alternative, you can store your .cer files in the www/certificates folder. - cordova.plugin.http.enableSSLPinning(true, function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); +```js +cordova.plugin.http.enableSSLPinning(true, function() { + console.log('success!'); +}, function() { + console.log('error :('); +}); +``` ### acceptAllCerts Accept all SSL certificates. Or disable accepting all certificates. This defaults to false. - cordova.plugin.http.acceptAllCerts(true, function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); +```js +cordova.plugin.http.acceptAllCerts(true, function() { + console.log('success!'); +}, function() { + console.log('error :('); +}); +``` ### validateDomainName This function was removed in v1.6.2. Domain name validation is disabled automatically when you enable "acceptAllCerts". @@ -122,7 +156,9 @@ This function was removed in v1.6.2. Domain name validation is disabled automati ### removeCookies Remove all cookies associated with a given URL. - cordova.plugin.http.removeCookies(url); +```js +cordova.plugin.http.removeCookies(url); +``` ### post Execute a POST request. Takes a URL, data, and headers. @@ -132,62 +168,69 @@ The success function receives a response object with 3 properties: status, data, Here's a quick example: - { - status: 200, - data: "{'id': 12, 'message': 'test'}", - headers: { - "content-length": "247" - } - } +```js +{ + status: 200, + data: '{"id": 12, "message": "test"}', + headers: { + 'content-length': '247' + } +} +``` Most apis will return JSON meaning you'll want to parse the data like in the example below: - cordova.plugin.http.post("https://google.com/", { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, function(response) { - // prints 200 - console.log(response.status); - try { - response.data = JSON.parse(response.data); - // prints test - console.log(response.data.message); - } catch(e) { - console.error("JSON parsing error"); - } - }, function(response) { - // prints 403 - console.log(response.status); - - //prints Permission denied - console.log(response.error); - }); +```js +cordova.plugin.http.post('https://google.com/', { + id: 12, + message: 'test' +}, { Authorization: 'OAuth2: token' }, function(response) { + // prints 200 + console.log(response.status); + try { + response.data = JSON.parse(response.data); + // prints test + console.log(response.data.message); + } catch(e) { + console.error('JSON parsing error'); + } +}, function(response) { + // prints 403 + console.log(response.status); + //prints Permission denied + console.log(response.error); +}); +``` #### failure The error function receives a response object with 3 properties: status, error and headers. **status** is the HTTP response code as numeric value. **error** is the error response from the server as a string. **headers** is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase. Here's a quick example: - { - status: 403, - error: "Permission denied", - headers: { - "content-length": "247" - } - } +```js +{ + status: 403, + error: 'Permission denied', + headers: { + 'content-length': '247' + } +} +``` ### get Execute a GET request. Takes a URL, parameters, and headers. See the [post](#post) documentation for details on what is returned on success and failure. - cordova.plugin.http.get("https://google.com/", { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, function(response) { - console.log(response.status); - }, function(response) { - console.error(response.error); - }); +```js +cordova.plugin.http.get('https://google.com/', { + id: 12, + message: 'test' +}, { Authorization: 'OAuth2: token' }, function(response) { + console.log(response.status); +}, function(response) { + console.error(response.error); +}); +``` ### put Execute a PUT request. Takes a URL, data, and headers. See the [post](#post) documentation for details on what is returned on success and failure. @@ -204,30 +247,34 @@ Execute a HEAD request. Takes a URL, parameters, and headers. See the [post](# ### uploadFile Uploads a file saved on the device. Takes a URL, parameters, headers, filePath, and the name of the parameter to pass the file along as. See the [post](#post) documentation for details on what is returned on success and failure. - cordova.plugin.http.uploadFile("https://google.com/", { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", "picture", function(response) { - console.log(response.status); - }, function(response) { - console.error(response.error); - }); +```js +cordova.plugin.http.uploadFile("https://google.com/", { + id: 12, + message: 'test' +}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', 'picture', function(response) { + console.log(response.status); +}, function(response) { + console.error(response.error); +}); +``` ### downloadFile Downloads a file and saves it to the device. Takes a URL, parameters, headers, and a filePath. See [post](#post) documentation for details on what is returned on failure. On success this function returns a cordova [FileEntry object](http://cordova.apache.org/docs/en/3.3.0/cordova_file_file.md.html#FileEntry). - cordova.plugin.http.downloadFile("https://google.com/", { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", function(entry) { - // prints the filename - console.log(entry.name); +```js +cordova.plugin.http.downloadFile("https://google.com/", { + id: 12, + message: 'test' +}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry) { + // prints the filename + console.log(entry.name); - // prints the filePath - console.log(entry.fullPath); - }, function(response) { - console.error(response.error); - }); + // prints the filePath + console.log(entry.fullPath); +}, function(response) { + console.error(response.error); +}); +``` ## Libraries diff --git a/test/js-mocha-specs.js b/test/js-mocha-specs.js index 10bb23c..5e7d6d6 100644 --- a/test/js-mocha-specs.js +++ b/test/js-mocha-specs.js @@ -58,7 +58,7 @@ describe('Advanced HTTP www interface', function() { http.get('url', {}, {}, noop, noop); }); - it('resolves host headers correctly', () => { + it('resolves host headers correctly (set without port number)', () => { mock(`${PLUGIN_ID}.cookie-handler`, { getCookieString: () => 'fakeCookieString' }); @@ -77,6 +77,25 @@ describe('Advanced HTTP www interface', function() { http.get('https://www.google.de/?gws_rd=ssl', {}, {}, noop, noop); }); + it('resolves host headers correctly (set with port number)', () => { + mock(`${PLUGIN_ID}.cookie-handler`, { + getCookieString: () => 'fakeCookieString' + }); + + mock('cordova/exec', (onSuccess, onFail, namespace, method, params) => { + const headers = params[2]; + headers.should.eql({ + Cookie: 'fakeCookieString', + myKey: 'myValue' + }); + }); + + loadHttp(); + + http.setHeader('www.google.de:8080', 'myKey', 'myValue'); + http.get('https://www.google.de:8080/?gws_rd=ssl', {}, {}, noop, noop); + }); + it('resolves request headers correctly', () => { mock(`${PLUGIN_ID}.cookie-handler`, { getCookieString: () => 'fakeCookieString'