Skip to content

Commit

Permalink
#76 [core] [helper] Add options function in the fecth and CORS, add C…
Browse files Browse the repository at this point in the history
…ORS config read in CORS
  • Loading branch information
pierr committed Jan 28, 2015
1 parent b475d7f commit 2155c3b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
40 changes: 27 additions & 13 deletions lib/core/cors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,42 @@
var ArgumentInvalidException = require('../helpers/custom_exception').ArgumentInvalidException;
/**
* Create a cors http request.
* @param method Type of method yopu want to reach.
* @param url Url to reach.
* @param method - Type of method yopu want to reach.
* @param url - Url to reach.
* @param options - The cors options.
* @returns {XMLHttpRequest}
*/
module.exports = function createCORSRequest(method, url) {
if(typeof method !== "string"){
module.exports = function createCORSRequest(method, url, options) {
options = options || {};
var isCORS = options.cors || require("../config").get().CORS;
if (typeof method !== "string") {
throw new ArgumentInvalidException('The method should be a string in GET/POST/PUT/DELETE', method);
}
if(typeof url !== "string"){
if (typeof url !== "string") {
throw new ArgumentInvalidException('The url should be a string', url);
}
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.setRequestHeader("Content-Type", "application/json");
// xhr.overrideMimeType("application/json");

//If CORS is not needed.
if (!isCORS) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);

} else {
// CORS not supported.
xhr = null;
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
}


return xhr;
}
2 changes: 1 addition & 1 deletion lib/core/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ var httpResponseParser = require('./http_response_parser');
module.exports = function fetch(obj, options) {
options = options || {};
options.parser = options.parser || httpResponseParser.parse;
var request = createCORSRequest(obj.type, obj.url);
var request = createCORSRequest(obj.type, obj.url, options);
if (!request) {
throw new Error('You cannot perform ajax request on other domains.');
}
Expand Down

0 comments on commit 2155c3b

Please sign in to comment.