Why am I getting an OPTIONS request instead of a GET request?

JqueryXmlhttprequestHttp GetHttp Options-Method

Jquery Problem Overview


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script>
$.get("http://example.com/", function(data) {
     alert(data);
});
</script>

it does an OPTIONS request to that URL, and then the callback is never called with anything.

When it isn't cross domain, it works fine.

Shouldn't jQuery just make the call with a <script> node and then do the callback when its loaded? I understand that I won't be able to get the result (since it is cross domain), but that's OK; I just want the call to go through. Is this a bug, or am I doing something wrong?

Jquery Solutions


Solution 1 - Jquery

According to MDN,

> Preflighted requests > > Unlike simple requests (discussed above), "preflighted" requests first > send an HTTP OPTIONS request header to the resource on the other > domain, in order to determine whether the actual request is safe to > send. Cross-site requests are preflighted like this since they may > have implications to user data. In particular, a request is > preflighted if: > > - It uses methods other than GET or POST. Also, if POST is used to send > request data with a Content-Type other than > application/x-www-form-urlencoded, multipart/form-data, or text/plain, > e.g. if the POST request sends an XML payload to the server using > application/xml or text/xml, then the request is preflighted. > - It sets custom headers in the request (e.g. the request uses a header such as > X-PINGOTHER)

Solution 2 - Jquery

Solution 3 - Jquery

If you're trying to POST

Make sure to JSON.stringify your form data and send as text/plain.

<form id="my-form" onSubmit="return postMyFormData();">
    <input type="text" name="name" placeholder="Your Name" required>
    <input type="email" name="email" placeholder="Your Email" required>
    <input type="submit" value="Submit My Form">
</form>

function postMyFormData() {
    
    var formData = $('#my-form').serializeArray();
    formData = formData.reduce(function(obj, item) {
        obj[item.name] = item.value;
        return obj;
    }, {});
    formData = JSON.stringify(formData);

    $.ajax({
        type: "POST",
        url: "https://website.com/path",
        data: formData,
        success: function() { ... },
        dataType: "text",
        contentType : "text/plain"
    });
}

Solution 4 - Jquery

I don't believe jQuery will just naturally do a JSONP request when given a URL like that. It will, however, do a JSONP request when you tell it what argument to use for a callback:

$.get("http://metaward.com/import/http://metaward.com/u/ptarjan?jsoncallback=?", function(data) {
     alert(data);
});

It's entirely up to the receiving script to make use of that argument (which doesn't have to be called "jsoncallback"), so in this case the function will never be called. But, since you stated you just want the script at metaward.com to execute, that would make it.

Solution 5 - Jquery

Just change the "application/json" to "text/plain" and do not forget the JSON.stringify(request):

var request = {Company: sapws.dbName, UserName: username, Password: userpass};
    console.log(request);
    $.ajax({
        type: "POST",
        url: this.wsUrl + "/Login",
        contentType: "text/plain",
        data: JSON.stringify(request),
      
        crossDomain: true,
    });

Solution 6 - Jquery

In fact, cross-domain AJAX (XMLHttp) requests are not allowed because of security reasons (think about fetching a "restricted" webpage from the client-side and sending it back to the server – this would be a security issue).

The only workaround are callbacks. This is: creating a new script object and pointing the src to the end-side JavaScript, which is a callback with JSON values (myFunction({data}), myFunction is a function which does something with the data (for example, storing it in a variable).

Solution 7 - Jquery

I had the same problem. My fix was to add headers to my PHP script which are present only when in dev environment.

This allows cross-domain requests:

header("Access-Control-Allow-Origin: *");

This tells the preflight request that it is OK for the client to send any headers it wants:

header("Access-Control-Allow-Headers: *");

This way there is no need to modify the request.

If you have sensitive data in your dev database that might potentially be leaked, then you might think twice about this.

Solution 8 - Jquery

In my case, the issue was unrelated to CORS since I was issuing a jQuery POST to the same web server. The data was JSON but I had omitted the dataType: 'json' parameter.

I did not have (nor did I add) a contentType parameter as shown in David Lopes' answer above.

Solution 9 - Jquery

I was able to fix it with the help of following headers

Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
Access-Control-Allow-Methods

If you are on Nodejs, here is the code you can copy/paste.

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH');
  next();
});

Solution 10 - Jquery

It's looking like Firefox and Opera (tested on mac as well) don't like the cross domainness of this (but Safari is fine with it).

You might have to call a local server side code to curl the remote page.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul TarjanView Question on Stackoverflow
Solution 1 - JqueryarturgrigorView Answer on Stackoverflow
Solution 2 - JqueryPaul TarjanView Answer on Stackoverflow
Solution 3 - JqueryDerek SoikeView Answer on Stackoverflow
Solution 4 - JqueryVoteyDiscipleView Answer on Stackoverflow
Solution 5 - JqueryDavid LopesView Answer on Stackoverflow
Solution 6 - JqueryAdrián NavarroView Answer on Stackoverflow
Solution 7 - JqueryfivebitView Answer on Stackoverflow
Solution 8 - JqueryGarDavisView Answer on Stackoverflow
Solution 9 - JqueryobaiView Answer on Stackoverflow
Solution 10 - JqueryhelloandreView Answer on Stackoverflow