Introduction to jQuery Ajax CORS
jQuery ajax CORS is nothing but cross-origin resource sharing. JQuery ajax CORS adds HTTP headers to cross-domain HTTP requests and answers. These headers indicate the request’s origin, and the server must declare whether it will provide resources to this origin using headers in the response. JQuery ajax CORS is a secure technique because of the exchange of headers.
What is jQuery Ajax CORS?
- JQuery ajax CORS is a cross-origin request if the script on our website runs on a domain, i.e., domain.com, and we want to request a resource from domain otherdomain.com using an XmlHttpRequest or an XDomainRequest. Browsers have always banned these requests for security reasons.
- The server must support CORS and signal that the client’s domain is allowed to do so. The benefit of this approach is that the browser handles it automatically, so web application developers don’t have to worry about it.
- The browser adds additional Origin and Referrer headers to indicate the requesting domain for simple cross-site requests, i.e., GETs and POSTs that don’t specify custom headers.
- When developing complicated client-side apps, it’s common to need to make Ajax calls to sites other than the one where our page came from at some point.
- Web application developers now have a browser-supported technique to make XmlHttpRequests to another domain in a secure manner, the Cross-Origin Resource Sharing (CORS) specification, which is now a candidate for W3C Recommendation.
- Finally, we can state that all of the major browsers support CORS. Firefox 3.5, Safari 4, and Chrome 3 were the first to see it.
- According to the CORS specification, browsers must preflight requests that meet the criteria. Therefore, other than GET, POST, and HEAD, use other request methods.
- Custom headers are available. Use Content-Types other than text/plain, application/x-www-form or multipart/form-data in request bodies.
- The OPTIONS request method is used in a preflight request to ensure that the server is CORS-enabled and that the type of request the client wants to submit is supported.
- In a cross-domain XmlHttpRequest, a browser will not communicate Cookies or HTTP Auth information.
- The credential attributes of the XmlHttpRequest or XDomainRequest must be set by the client application to indicate that they should be sent.
- This value is false and unset by default. If we wanted to include any cookies that the user may have obtained for the domain otherdomain.com along with the request to access the resource called some-resource at otherdomain.com
Using jQuery ajax CORS
- There are numerous solutions to CORS that have been used to handle the cross-origin communication constraint in web applications that must run in browsers that do not support CORS.
- JSONP is a method for circumventing the same-origin security restriction using the HTML script element exception.
- Script tags can load JavaScript from a separate domain, and query parameters can be added to the script URI to convey information about the resources we want to access to the server hosting the script.
- OpenAjax is a JavaScript Ajax module that allows many client-side components to be integrated into one web application.
- The OpenAjax Hub JavaScript module allows trusted and untrusted components to coexist on the same page and communicate with one another.
- The framework has a security manager that enables the application to define component messaging security policies.
- Easy XDM is a JavaScript package that permits cross-domain communication using strings via iframes. It functions similarly to OpenAjax Hub but without the security manager.
- The iframe that has been proxied is an iframe from the domain we want to communicate with on our page.
- This presupposes that we can host pages on this additional domain. The JavaScript in the iframe acts as a reverse proxy to the server that contains the resources we want to use.
- The post-message protocol will communicate between our application and the rest proxy.
CORS error jQuery ajax
- The refusal of a browser to access a remote resource is a typical issue for developers. This usually occurs when utilizing the jQuery Ajax interface, the Fetch API, or basic XMLHttpRequest to make an AJAX cross-domain request.
- As a result, the AJAX request is not completed, and no data is returned. Instead, the browser sends an Origin header with the current domain value when making a cross-origin request. CORS is a technique that describes a procedure for determining whether a web page can access a resource from a different origin by interacting with the browser and the web server.
- Single request that is straightforward A straightforward cross-domain request consists of the following elements.
- When making a cross-origin request, the browser sends an Origin header with the current domain value.
- CORS does not appear to be supported by this server. The server answer is missing the “Access-Control-Allow-Origin” header.
- By including custom headers, we are triggering a preflight request. The browser agent automatically adds special headers to outbound same-origin AJAX connections to implement the Distributed Tracing functionality.
- When the AJAX request is returned with a redirect status code, the browser will immediately make the same AJAX call to the redirected URL.
- APIs are the stitches that hold a rich web experience together. However, cross-domain requests are limited to JSON-P or setting up a custom proxy in the browser.
- W3C’s Cross-Origin Resource Sharing specification allows browsers to communicate across domains. CORS enables developers to use the same idioms as same-domain requests by building on top of the XMLHttpRequest object.
- Below is the example of a CORS error jQuery ajax is as follows.
Code –
function afficheorga(a){
$.ajax({
url: "https://cubber.zendesk.com/api/ organizations.json",
type: 'GET',
dataType: 'jsonp',
CORS: true ,
contentType:'application/json',
secure: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
console.log(data.organizations[0].name);
var organisation = data.organizations[0].name;
$("#company").text(organisation);
}
}) }
JQuery ajax CORS code example
Below is the example of jQuery ajax CORS are as follows.
Example –
<!DOCTYPE html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jQuery/3.3.1/jQuery.min.js"></script>
<script>
var settings = {
'cache': false,
'dataType': "jsonp",
"async": true,
"crossDomain": true,
"url": "https://maps.googleapis.com/maps/api/distancematrix/json?units ",
"method": "GET",
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
</script>
</head>
<body>
<p id="pid">JQuery ajax Code executed successfully.</p>
</body>
</html>
Conclusion
JQuery ajax CORS is a cross-origin request if the script on our website runs on a domain, i.e., domain.com, and we want to request resources from domain otherdomain.com using an XmlHttpRequest or an XDomainRequest. JQuery ajax CORS adds HTTP headers to cross-domain HTTP requests and answers.
Recommended Articles
This is a guide to jQuery Ajax CORS. Here we discuss the example of jQuery ajax CORS along with the codes and outputs. You may also have a look at the following articles to learn more –
- jQuery array push
- jQuery insert element
- jQuery insert
- jquery ajax url
Содержание
- jQuery Ajax CORS
- JQuery Training Course
- Java Servlet Training Course
- JavaFX Training Course
- Introduction to jQuery Ajax CORS
- What is jQuery Ajax CORS?
- Using jQuery ajax CORS
- CORS error jQuery ajax
- JQuery ajax CORS code example
- Conclusion
- Recommended Articles
- jQuery.ajax()
- jQuery.ajax( url [, settings ] ) Returns: jqXHR
- version added: 1.5 jQuery.ajax( url [, settings ] )
- version added: 1.0 jQuery.ajax( [settings ] )
- The jqXHR Object
- Callback Function Queues
- Data Types
- Sending Data to the Server
- Advanced Options
jQuery Ajax CORS
jQuery Tutorial
JQuery Training Course
Java Servlet Training Course
JavaFX Training Course
Introduction to jQuery Ajax CORS
jQuery ajax CORS is nothing but cross-origin resource sharing. JQuery ajax CORS adds HTTP headers to cross-domain HTTP requests and answers. These headers indicate the request’s origin, and the server must declare whether it will provide resources to this origin using headers in the response. JQuery ajax CORS is a secure technique because of the exchange of headers.
What is jQuery Ajax CORS?
- JQuery ajax CORS is a cross-origin request if the script on our website runs on a domain, i.e., domain.com, and we want to request a resource from domain otherdomain.com using an XmlHttpRequest or an XDomainRequest. Browsers have always banned these requests for security reasons.
- The server must support CORS and signal that the client’s domain is allowed to do so. The benefit of this approach is that the browser handles it automatically, so web application developers don’t have to worry about it.
- The browser adds additional Origin and Referrer headers to indicate the requesting domain for simple cross-site requests, i.e., GETs and POSTs that don’t specify custom headers.
- When developing complicated client-side apps, it’s common to need to make Ajax calls to sites other than the one where our page came from at some point.
- Web application developers now have a browser-supported technique to make XmlHttpRequests to another domain in a secure manner, the Cross-Origin Resource Sharing (CORS) specification, which is now a candidate for W3C Recommendation.
- Finally, we can state that all of the major browsers support CORS. Firefox 3.5, Safari 4, and Chrome 3 were the first to see it.
- According to the CORS specification, browsers must preflight requests that meet the criteria. Therefore, other than GET, POST, and HEAD, use other request methods.
- Custom headers are available. Use Content-Types other than text/plain, application/x-www-form or multipart/form-data in request bodies.
- The OPTIONS request method is used in a preflight request to ensure that the server is CORS-enabled and that the type of request the client wants to submit is supported.
- In a cross-domain XmlHttpRequest, a browser will not communicate Cookies or HTTP Auth information.
- The credential attributes of the XmlHttpRequest or XDomainRequest must be set by the client application to indicate that they should be sent.
- This value is false and unset by default. If we wanted to include any cookies that the user may have obtained for the domain otherdomain.com along with the request to access the resource called some-resource at otherdomain.com
Using jQuery ajax CORS
- There are numerous solutions to CORS that have been used to handle the cross-origin communication constraint in web applications that must run in browsers that do not support CORS.
- JSONP is a method for circumventing the same-origin security restriction using the HTML script element exception.
- Script tags can load JavaScript from a separate domain, and query parameters can be added to the script URI to convey information about the resources we want to access to the server hosting the script.
- OpenAjax is a JavaScript Ajax module that allows many client-side components to be integrated into one web application.
- The OpenAjax Hub JavaScript module allows trusted and untrusted components to coexist on the same page and communicate with one another.
- The framework has a security manager that enables the application to define component messaging security policies.
- Easy XDM is a JavaScript package that permits cross-domain communication using strings via iframes. It functions similarly to OpenAjax Hub but without the security manager.
- The iframe that has been proxied is an iframe from the domain we want to communicate with on our page.
- This presupposes that we can host pages on this additional domain. The JavaScript in the iframe acts as a reverse proxy to the server that contains the resources we want to use.
- The post-message protocol will communicate between our application and the rest proxy.
CORS error jQuery ajax
- The refusal of a browser to access a remote resource is a typical issue for developers. This usually occurs when utilizing the jQuery Ajax interface, the Fetch API, or basic XMLHttpRequest to make an AJAX cross-domain request.
- As a result, the AJAX request is not completed, and no data is returned. Instead, the browser sends an Origin header with the current domain value when making a cross-origin request. CORS is a technique that describes a procedure for determining whether a web page can access a resource from a different origin by interacting with the browser and the web server.
- Single request that is straightforward A straightforward cross-domain request consists of the following elements.
- When making a cross-origin request, the browser sends an Origin header with the current domain value.
- CORS does not appear to be supported by this server. The server answer is missing the “Access-Control-Allow-Origin” header.
- By including custom headers, we are triggering a preflight request. The browser agent automatically adds special headers to outbound same-origin AJAX connections to implement the Distributed Tracing functionality.
- When the AJAX request is returned with a redirect status code, the browser will immediately make the same AJAX call to the redirected URL.
- APIs are the stitches that hold a rich web experience together. However, cross-domain requests are limited to JSON-P or setting up a custom proxy in the browser.
- W3C’s Cross-Origin Resource Sharing specification allows browsers to communicate across domains. CORS enables developers to use the same idioms as same-domain requests by building on top of the XMLHttpRequest object.
- Below is the example of a CORS error jQuery ajax is as follows.
Code –
Web development, programming languages, Software testing & others
JQuery ajax CORS code example
Below is the example of jQuery ajax CORS are as follows.
Example –
Conclusion
JQuery ajax CORS is a cross-origin request if the script on our website runs on a domain, i.e., domain.com, and we want to request resources from domain otherdomain.com using an XmlHttpRequest or an XDomainRequest. JQuery ajax CORS adds HTTP headers to cross-domain HTTP requests and answers.
Recommended Articles
This is a guide to jQuery Ajax CORS. Here we discuss the example of jQuery ajax CORS along with the codes and outputs. You may also have a look at the following articles to learn more –
Источник
jQuery.ajax()
jQuery.ajax( url [, settings ] ) Returns: jqXHR
Description: Perform an asynchronous HTTP (Ajax) request.
version added: 1.5 jQuery.ajax( url [, settings ] )
version added: 1.0 jQuery.ajax( [settings ] )
Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.
When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false . For example, < a: «bc», d: «e,f» >is converted to the string «a=bc&d=e%2Cf» . If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, < a: [1,2] >becomes the string «a%5B%5D=1&a%5B%5D=2» with the default traditional: false setting.
When data is passed as a string it should already be encoded using the correct encoding for contentType , which by default is application/x-www-form-urlencoded .
In requests with dataType: «json» or dataType: «jsonp» , if the string contains a double question mark ( ?? ) anywhere in the URL or a single question mark ( ? ) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g. jQuery21406515378922229067_1479880736745 ).
An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.
In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.
The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.
At its simplest, the $.ajax() function can be called with no arguments:
Note: Default settings can be set globally by using the $.ajaxSetup() function.
This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.
The jqXHR Object
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.
As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
- jqXHR.done(function( data, textStatus, jqXHR ) <>);
An alternative construct to the success callback option, refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) <>);
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) < >); (added in jQuery 1.6)
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function’s arguments are the same as those of .done() : data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail() : the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) <>, function( jqXHR, textStatus, errorThrown ) <>);
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
Deprecation Notice: The jqXHR.success() , jqXHR.error() , and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done() , jqXHR.fail() , and jqXHR.always() instead.
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
For backward compatibility with XMLHttpRequest , a jqXHR object will expose the following properties and methods:
- readyState
- responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
- status
- statusText (may be an empty string in HTTP/2)
- abort( [ statusText ] )
- getAllResponseHeaders() as a string
- getResponseHeader( name )
- overrideMimeType( mimeType )
- setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
- statusCode( callbacksByStatusCode )
No onreadystatechange mechanism is provided, however, since done , fail , always , and statusCode cover all conceivable requirements.
Callback Function Queues
The beforeSend , error , dataFilter , success and complete options all accept callback functions that are invoked at the appropriate times.
As of jQuery 1.5, the fail and done , and, as of jQuery 1.6, always callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods, which are implemented internally for these $.ajax() callback hooks.
The callback hooks provided by $.ajax() are as follows:
- beforeSend callback option is invoked; it receives the jqXHR object and the settings object as parameters.
- error callback option is invoked, if the request fails. It receives the jqXHR , a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: «abort», «timeout», «No Transport».
- dataFilter callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success .
- success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.
- Promise callbacks — .done() , .fail() , .always() , and .then() — are invoked, in the order they are registered.
- complete callback option fires, when the request finishes, whether in failure or success. It receives the jqXHR object, as well as a string containing the success or error code.
Data Types
Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.
The available data types are text , html , xml , json , jsonp , and script .
If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.
If xml is specified, the response is parsed using jQuery.parseXML before being passed, as an XMLDocument , to the success handler. The XML document is made available through the responseXML property of the jqXHR object.
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.
If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.
For more information on JSONP, see the original post detailing its use.
Sending Data to the Server
By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.
Advanced Options
The global option prevents handlers registered using .ajaxSend() , .ajaxError() , and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with .ajaxSend() if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false . See the descriptions of these methods below for more details.
If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.
Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.
By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false . To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true .
The scriptCharset allows the character set to be explicitly specified for requests that use a
Источник
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. This is set on the server-side and there is nothing you can do from the client-side to change that setting, that is up to the server/API. There are some ways to get around it tho.
Sources : MDN — HTTP Access Control | Wiki — CORS
CORS is set server-side by supplying each request with additional headers which allow requests to be requested outside of the own domain, for example to your localhost
. This is primarily set by the header:
Access-Control-Allow-Origin
The header specifies which origins (domains/servers) the information can be accessed from. To enable CORS you usually set it to allow access from all origins with a wildcard (*):
Access-Control-Allow-Origin: *
or you can tell the server to serve content to specific domains, every other domain will be blocked from showing the content in a browser:
Access-Control-Allow-Origin: https://developer.mozilla.org
Bypass client-side for production
Proxy
WARNING
: Great services, but you are dependent on these services to work, if they break or go down, so does your app
You can use a service that proxies your request and automatically enable CORS
for your:
- https://cors-anywhere.herokuapp.com/
- More Proxies here
Then you have to call your API by prepending one of these URLs to your request, for example:
- https://cors-anywhere.herokuapp.com/http://yourapi.com
JSONP
WARNING
: This isn’t allowed on every API and may break when calling certain APIS
You can bypass CORS in production using JSONP
which stands for JSON with Padding and is kinda also a ‘hack’. But it is a widely used hack which many APIs support. You are not sending a pure JSON-request but you are wrapping your data in a function that gets evaluated. JSONP
explained in the link below:
JSONP explained in layman terms @ Stack Overflow
jQuery $.ajax() JSONP
The simplest way to handle JSON is through the $.ajax()
-function in jQuery as it handles the real dirty parts automatically:
$.ajax({ method: 'GET', url: 'http://localhost:3000', dataType: 'jsonp', //change the datatype to 'jsonp' works in most cases success: (res) => { console.log(res); } })
jQuery: Working with JSONP
fetch-jsonp library
There is no native implementation of JSONP
in either XMLHttpRequest
or fetch
. If you want to use fetch
you can use this 1kb library which handle JSONP
with fetch
:
fetch-jsonp @ GitHub
- Link the code in your
index.html
:
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.0.6/fetch-jsonp.min.js"></script>
- And use like fetch but with the function
fetchJsonp
:
fetchJsonp('http://localhost:3000') .then(res => res.json()) .then(json => console.log(json));
Vanilla JavaScript jsonp
It can be done in regular JavaScript as well of course:
- Simple JSONP in vanilla JS
Bypass during development 🔨
WARNING
: All users who uses your site must use this hack so this is only intended for bypassing temporarily and for testing during development. You can’t assume it will work for your end users. This is just a client-side quick fix and it doesn’t change the way the server handles the request. This will make your site work on your computer and every other browser that also has this extension installed.
If you have Chrome you can use a extensions which ‘hacks’ the response/request. Be sure to disable it when not testing as it can break other sites, GitHub have been known to have problems with this extension if you have it enabled when browsing or using GitHub.
Allow-Control-Allow-Origin: * @ Chrome Web Store
Доброго времени суток.
Мне нужно реализовать авторизацию Phonegap-приложения на сервере через REST-API. Тестирую код приложения в Хроме. При выключенном плагине CORS не работают GET запросы, выдает ошибку
XMLHttpRequest cannot load api2.xxx.com/auth?api_key=yyy. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘mmm.local’ is therefore not allowed access.
При включенном плагине CORS GET -запрос уходит и возвращает все необходимые данные, после чего должен идти второй POST-запрос. Он не выполняется, возвращает ошибку такого плана
OPTIONS api2.xxx.com/token
yyy.local/:1 XMLHttpRequest cannot load api2.xxx.com/token. Response for preflight has invalid HTTP status code 405
Выдает 405 ошибку.
Я просмотрел материал по CORS, но те примеры не совсем подходят под мое задание.
Если можно, подскажите, в какую сторону копать, нужно ли настраивать CORS на сервере или что-то добавить в AJAX-запрос , чтобы выполнялись и POST и GET запросы без дополнительных плагинов(когда приложение по сути будет самостоятельной единицей.)
Привожу фрагмент кода для авторизации.
Заранее спасибо
$.ajax({
type: "POST",
crossDomain: true,
url: config.apiUrl + "/token",
processData: false,
contentType: 'application/json',
data: JSON.stringify(ss),
success: function (response) {
localStorage.accesstoken = response.AccessToken;
console.log(response);
if (localStorage.getItem('accesstoken') == null || localStorage.getItem('accesstoken') == '') {
alert('Not getting Access Token, Please try again');
}
else {
if (localStorage.username && localStorage.password) {
localStorage.login_token = 'true';
}
if (func !== undefined) {
func();
}
}
Description: Perform an asynchronous HTTP (Ajax) request.
The $.ajax()
function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get()
and .load()
are available and are easier to use. If less common options are required, though, $.ajax()
can be used more flexibly.
At its simplest, the $.ajax()
function can be called with no arguments:
Note: Default settings can be set globally by using the $.ajaxSetup()
function.
This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.
The jqXHR Object
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax()
as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object. For example, it contains responseText
and responseXML
properties, as well as a getResponseHeader()
method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR
object simulates native XHR functionality where possible.
As of jQuery 1.5.1, the jqXHR
object also contains the overrideMimeType()
method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType()
method may be used in the beforeSend()
callback function, for example, to modify the response content-type header:
1 2 3 4 5 6 7 8 9 10 11 |
|
The jqXHR objects returned by $.ajax()
as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax()
request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
-
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to
deferred.done()
for implementation details. -
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the
.fail()
method replaces the deprecated.error()
method. Refer todeferred.fail()
for implementation details. -
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); (added in jQuery 1.6)
An alternative construct to the complete callback option, the
.always()
method replaces the deprecated.complete()
method.In response to a successful request, the function’s arguments are the same as those of
.done()
: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of.fail()
: the jqXHR object, textStatus, and errorThrown. Refer todeferred.always()
for implementation details. -
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the
.done()
and.fail()
methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer todeferred.then()
for implementation details.
Deprecation Notice: The jqXHR.success()
, jqXHR.error()
, and jqXHR.complete()
callbacks are removed as of jQuery 3.0. You can use jqXHR.done()
, jqXHR.fail()
, and jqXHR.always()
instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
The this
reference within all callbacks is the object in the context
option passed to $.ajax
in the settings; if context
is not specified, this
is a reference to the Ajax settings themselves.
For backward compatibility with XMLHttpRequest
, a jqXHR
object will expose the following properties and methods:
-
readyState
-
responseXML
and/orresponseText
when the underlying request responded with xml and/or text, respectively -
status
-
statusText
(may be an empty string in HTTP/2) -
abort( [ statusText ] )
-
getAllResponseHeaders()
as a string -
getResponseHeader( name )
-
overrideMimeType( mimeType )
-
setRequestHeader( name, value )
which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one -
statusCode( callbacksByStatusCode )
No onreadystatechange
mechanism is provided, however, since done
, fail
, always
, and statusCode
cover all conceivable requirements.
Callback Function Queues
The beforeSend
, error
, dataFilter
, success
and complete
options all accept callback functions that are invoked at the appropriate times.
As of jQuery 1.5, the fail
and done
, and, as of jQuery 1.6, always
callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods, which are implemented internally for these $.ajax()
callback hooks.
The callback hooks provided by $.ajax()
are as follows:
-
beforeSend
callback option is invoked; it receives thejqXHR
object and thesettings
object as parameters. -
error
callback option is invoked, if the request fails. It receives thejqXHR
, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: «abort», «timeout», «No Transport». -
dataFilter
callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value ofdataType
, and must return the (possibly altered) data to pass on tosuccess
. -
success
callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and thejqXHR
object. -
Promise callbacks —
.done()
,.fail()
,.always()
, and.then()
— are invoked, in the order they are registered. -
complete
callback option fires, when the request finishes, whether in failure or success. It receives thejqXHR
object, as well as a string containing the success or error code.
Data Types
Different types of response to $.ajax()
call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType
option. If the dataType
option is provided, the Content-Type header of the response will be disregarded.
The available data types are text
, html
, xml
, json
, jsonp
, and script
.
If text
or html
is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText
property of the jqXHR
object.
If xml
is specified, the response is parsed using jQuery.parseXML
before being passed, as an XMLDocument
, to the success handler. The XML document is made available through the responseXML
property of the jqXHR
object.
If json
is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON
property of the jqXHR
object.
If script
is specified, $.ajax()
will execute the JavaScript that is received from the server before passing it on to the success handler as a string.
If jsonp
is specified, $.ajax()
will automatically append a query string parameter of (by default) callback=?
to the URL. The jsonp
and jsonpCallback
properties of the settings passed to $.ajax()
can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax()
will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax()
success handler.
For more information on JSONP, see the original post detailing its use.
Sending Data to the Server
By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type
option. This option affects how the contents of the data
option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.
The data
option can contain either a query string of the form key1=value1&key2=value2
, or an object of the form {key1: 'value1', key2: 'value2'}
. If the latter form is used, the data is converted into a query string using jQuery.param()
before it is sent. This processing can be circumvented by setting processData
to false
. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType
option from application/x-www-form-urlencoded
to a more appropriate MIME type.
Advanced Options
The global
option prevents handlers registered using .ajaxSend()
, .ajaxError()
, and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with .ajaxSend()
if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false
. See the descriptions of these methods below for more details.
If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username
and password
options.
Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup()
rather than being overridden for specific requests with the timeout
option.
By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache
to false
. To cause the request to report failure if the asset has not been modified since the last request, set ifModified
to true
.
The scriptCharset
allows the character set to be explicitly specified for requests that use a <script>
tag (that is, a type of script
or jsonp
). This is useful if the script and host page have differing character sets.
The first letter in Ajax stands for «asynchronous,» meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async
option to $.ajax()
defaults to true
, indicating that code execution can continue after the request is made. Setting this option to false
(and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.
The $.ajax()
function returns the XMLHttpRequest
object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr
option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling .abort()
on the object will halt the request before it completes.
Extending Ajax
As of jQuery 1.5, jQuery’s Ajax implementation includes prefilters, transports, and converters that allow you to extend Ajax with a great deal of flexibility.
Using Converters
$.ajax()
converters support mapping data types to other data types. If, however, you want to map a custom data type to a known type (e.g json
), you must add a correspondence between the response Content-Type and the actual data type using the contents
option:
1 2 3 4 5 6 7 8 9 10 11 |
|
This extra object is necessary because the response Content-Types and data types never have a strict one-to-one correspondence (hence the regular expression).
To convert from a supported type (e.g text
, json
) to a custom data type and back again, use another pass-through converter:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The above now allows passing from text
to mycustomtype
and then mycustomtype
to json
.
Examples:
Save some data to the server and notify the user once it’s complete.
1 2 3 4 5 6 7 8 |
|
Retrieve the latest version of an HTML page.
1 2 3 4 5 6 7 |
|
Send an xml document as data to the server. By setting the processData
option to false
, the automatic conversion of data to strings is prevented.
1 2 3 4 5 6 7 8 |
|
Send an id as data to the server, save some data to the server, and notify the user once it’s complete. If the request fails, alert the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Load and execute a JavaScript file.
В ходе использования программного интерфейса приложения (API) XMLHttpRequest скриптового языка браузеров JavaScript, обычно в тандеме с технологией AJAX (Asynchronous JavaScript And XML), могут возникать различные ошибки CORS (Cross-origin resource sharing) при попытке доступа к ресурсам другого домена.
Здесь мы условились о том, что:
- src.example.org — это домен, с которого отправляются XMLHttpRequest кросс-доменные запросы
- target.example.com/example.php — это домен и скрипт /example.php, на который XMLHttpRequest кросс-доменные запросы отправляются
Перечисленные ниже CORS ошибки приводятся в том виде, в котором они выдавались в консоль веб-браузера.
https://target.example.com/example.php в данном примере фактически был размещён на сервере страны отличной от Украины и посредством CURL предоставлял доступ к российскому сервису проверки правописания от Яндекса, — как извесно доступ к сервисам Яндекса из Украины был заблокирован большинством Интернет-провайдеров.
При попытке проверить правописание в редакторе выдавалась ошибка: «The spelling service was not found: (https://target.example.com/example.php)«
Причина: отсутствует заголовок CORS ‘Access-Control-Allow-Origin’
«NetworkError: 403 Forbidden — https://target.example.com/example.php»
example.php
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: отсутствует заголовок CORS ‘Access-Control-Allow-Origin’).
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: не удалось выполнить запрос CORS).
Решение: отсутствует заголовок CORS ‘Access-Control-Allow-Origin’
CORS для src.example.org должно быть разрешено на стороне сервера принимающего запросы — это можно сделать в .htaccess следующим образом:
<Files ~ "(example)+.php"> Header set Access-Control-Allow-Origin "https://src.example.org" </Files>
Причина: неудача канала CORS preflight
«NetworkError: 403 Forbidden — https://target.example.com/example.php» example.php
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: неудача канала CORS preflight).
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: не удалось выполнить запрос CORS).
Решение: неудача канала CORS preflight
Причины здесь могут быть разные, среди которых может быть запрет некоторых ИП на стороне брандмауэра, либо ограничения на методы запроса в том же .htaccess строкой: «RewriteCond %{REQUEST_METHOD} !^(post|get) [NC,OR]
«.
Во-втором случае это может быть зафиксировано в лог-файле ошибок сервера:
xxx.xxx.xx.xxx [07/May/2018:09:55:15 +0300] «OPTIONS /example.php HTTP/1.1» 403 «Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0» «Referer: -«
Примечание:
Нужно помнить, что ИП-адрес в лог-файле сервера принадлежит клиенту/браузеру, а не удалённому серверу src.example.org на страницах которого в браузере клиента был инициирован CORS (кросс-доменный) запрос!
В случае с .htaccess
строку подправим до такого состояния: «RewriteCond %{REQUEST_METHOD} !^(post|get|options) [NC,OR]
«.
Причина: отсутствует токен ‘x-requested-with’ в заголовке CORS ‘Access-Control-Allow-Headers’ из канала CORS preflight
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: отсутствует токен ‘x-requested-with’ в заголовке CORS ‘Access-Control-Allow-Headers‘ из канала CORS preflight).
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: не удалось выполнить запрос CORS).
Решение: отсутствует токен ‘x-requested-with’ в заголовке CORS ‘Access-Control-Allow-Headers’ из канала CORS preflight
Посредством .htaccess
добавим заголовок Access-Control-Allow-Headers:
<Files ~ "(example)+.php"> Header set Access-Control-Allow-Origin "https://src.example.org" Header set Access-Control-Allow-Headers: "X-Requested-With" </Files>
Access-Control-Allow-Origin для множества доменов
Заголовок Access-Control-Allow-Origin допускает установку только одного источника, однако при необходимости разрешения CORS для множества источников в .htaccess можно извратится следующим образом:
##### ---+++ BEGIN MOD HEADERS CONFIG +++--- <IfModule mod_headers.c> <Files ~ "(example)+.php"> #Header set crossDomain: true # ## Allow CORS from one domain #Header set Access-Control-Allow-Origin "https://src.example.org" ## Allow CORS from multiple domain SetEnvIf Origin "http(s)?://(www.)?(example.org|src.example.org)$" AccessControlAllowOrigin=$0 Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin # ## Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token Header set Access-Control-Allow-Headers: "X-Requested-With" # ## "GET, POST" Header set Access-Control-Allow-Methods "POST" # #Header set Access-Control-Allow-Credentials true #Header set Access-Control-Max-Age 60 </Files> </IfModule> ##### ---+++// END MOD HEADERS CONFIG +++---
Contents
- 1 The Problem
- 2 CORS vs JSONP
- 3 How to Pass Cookies on a Cross-Domain AJAX Request from Browser to Server
- 3.1 Configuring the AJAX Request
- 3.1.1 AJAX Parameter: withCredentials
- 3.1.2 AJAX Request
- 3.2 Server Headers
- 3.2.1 Header: Access-Control-Allow-Origin
- 3.2.2 Header: Access-Control-Allow-Credentials
- 3.1 Configuring the AJAX Request
The Problem
Your code makes an AJAX request (with jQuery, though this issue isn’t specific to jQuery) cross-domain and the server expects the cookies from the browser to be passed. However they are not sent in the request from the browser.
CORS vs JSONP
I’m not going to go into full details here – just hit on the tip top level. A plethora of information is available on the internet for these topics.
CORS (Cross-origin resource sharing) is a mechanism implemented by browsers to ensure that malicious requests to a server can’t be made – it’s a restriction method. It respects the Same-origin policy for security reasons.
First off, JSONP technically is a way to solve this problem, however I don’t advise it as the correct solution. It is an old and outdated technology and has security flaws. The basics of it is that a request to the server (with cookies) is made by the browser for a javascript function. A function is returned and the browser can then use it to process the response as needed.
How to Pass Cookies on a Cross-Domain AJAX Request from Browser to Server
There are two things that need to be done here:
- Configure your AJAX request to pass cookies
- Set the response headers to conform with CORS
Configuring the AJAX Request
You need to tell your AJAX request to pass credentials with this bit of code:
xhrFields: { withCredentials: true }, |
AJAX Parameter: withCredentials
Reference: MDN XMLHttpRequest.withCredentials
This parameter indicates if a cross-domain request should send credentials (which include cookies, TLS certificates, authorization headers, etc.).
AJAX Request
Here is a full example of what the basic AJAX request should look like.
jQuery.ajax({ url: «http://subdomain.yourserver.com/getinformation/», dataType: ‘json’, xhrFields: { withCredentials: true }, success: function(data) { console.log(data); } }); |
The browser is now passing cookies (credentials) to the server.
The server now needs to respect the CORS request and respond with the correct headers. There are two headers that need to be set for this to work roundtrip.
This needs to be set to the domain from which the browser made the request. So if the URL in the browser is:
http://www.yourserver.com
and makes the AJAX request to:
http://subdomain.yourserver.com/getinformation/
then this header needs to be set as so:
Access—Control—Allow—Origin:http://www.yourserver.com |
What this header says is that this is the only domain that is allowed to make this cross-origin request – essentially the two domains are the same domain. A request from any other domain will fail the Same-origin policy of CORS and the request will fail.
Reference: MDN Access-Control-Allow-Origin
This header needs to be set to true in this scenario.
Access—Control—Allow—Credentials:true |
This is simply a partner header to the withCredentials parameter passed in the AJAX request. It’s saying that credentials are allowed to be passed through this request and response.
Reference: MDN Access-Control-Allow-Credentials
Learn how to execute an asynchronous request to another domain without any problem in javascript
If you’re a curious developer in some point of your life you may already faced (or you will face) the cross-domain/same-origin policy. This policy says that you can’t retrieve information from another domain except yours (www.mydomain.com cannot execute async calls to www.otherdomain.com). Fortunately, there is a free proxy server named CORS Anywhere which adds CORS headers to the proxied request.
Solution
To solve this issue easily with javascript, we will make an ajax request as you always do with XMLHttpRequest
or jQuery ajax
but we’ll use the cors-anywhere service, which allow us to bypass this problem. CORS Anywhere is a NodeJS reverse proxy which adds CORS headers to the proxied request hosted in herokuapp.
The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to «http». If port 443 is specified, the protocol defaults to «https». This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed.
You only have to add as prefix to your request URL https://cors-anywhere.herokuapp.com, then the problem will be solved.
jQuery
// In this example, if you make an ajax request to the following website
var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';
// But if you make it from a browser, then it will work without problem ...
// However to make it work, we are going to use the cors-anywhere free service to bypass this
var proxy = 'https://cors-anywhere.herokuapp.com/';
$.ajax({
// The proxy url expects as first URL parameter the URL to be bypassed
// https://cors-anywhere.herokuapp.com/{my-url-to-bypass}
url: proxy + myUrl,
complete:function(data){
console.log(data);
}
});
Or using the shortcuts of $.get
, $.getJSON
or $.post
:
var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';
var proxy = 'https://cors-anywhere.herokuapp.com/';
var finalURL = proxy + myUrl;
// With the get JSON (frequently used) method
$.getJSON(finalURL, function( data ) {
console.log(data);
});
// With the get method
$.get(finalURL, function( data ) {
console.log(data);
});
// With the post method
$.post(finalURL, function( data ) {
console.log(data);
});
XMLHttpRequest
// In this example, if you make an ajax request to the following website
var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';
// But if you make it from a browser, then it will work without problem ...
// However to make it work, we are going to use the cors-anywhere free service to bypass this
var proxy = 'https://cors-anywhere.herokuapp.com/';
// Execute request
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function () {
console.log(this.responseText);
});
// Or post, etc
oReq.open("GET", proxy + myUrl);
oReq.send();
There are only two limitations with this approach:
- Cookies are not proxied
- Requesting user credentials is disallowed
Have fun !