V
V
vostotskiy2016-02-22 10:53:30
JavaScript
vostotskiy, 2016-02-22 10:53:30

How to implement CORS for an AJAX request with jQuery?

Good day.
I need to implement Phonegap application authorization on the server via REST-API. I'm testing the application code in Chrome. When the CORS plugin is disabled, GET requests do not work, it gives an error
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.
With the CORS GET plugin enabled, the request leaves and returns all the necessary data, after which the second POST request should go. It fails, returns an error like this
OPTIONS api2.xxx.com/token
yyy.local/:1 XMLHttpRequest cannot load api2.xxx.com/token. Response for preflight has invalid HTTP status code 405

Throws a 405 error.
I looked at the CORS material, but those examples do not quite fit my task.
If possible, tell me in which direction to dig, do I need to configure CORS on the server or add something to the AJAX request so that both POST and GET requests are made without additional plugins (when the application is essentially an independent unit.)
Here is a code snippet for authorization.
Thanks in advance

$.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();
                        }
                    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-02-22
Protko @Fesor

1) CORS is configured on the server
2) CORS is not needed for Phonegap / Cordova, this is a feature of the browser and not webview.
3) for development, you can raise a proxy server (there are ready ones, just look in npm) which will add CORS headers to you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question