0

I have an HTML form in my page. On submit of the form, I am trying to send a JSON file (constructed from the html form) with POST method in a Web Service which runs on my network:

$('form').on('submit', function (e) {
    e.preventDefault();
    var formData = {};
    formData["productId"] = $('#productId').val(); //<--This the value from the html form
    var json = JSON.stringify(formData); //<-- This is the json file that I try to send

    $.ajax({
        type: 'POST',
        method: 'POST',
        url: 'http://link_of_web_service',
        data: json,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            alert(data);
        }
    });
});

But, in the console of the Web Service, I am getting this error message:

Unsupported HTTP method 'OPTIONS' was requested from '192.168.0.251:52743'

I can't figure out why the web service interprets the sending method as OPTIONS and not as POST that I have set. The json is not empty, as the console.log(json) prints

{ "productId":"703156124"}

The Web Service that I am setting is from Bartender software.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
yaylitzis
  • 5,354
  • 17
  • 62
  • 107
  • 2
    It's because you're making a cross-domain request. Therefore a 'pre-flight' OPTIONS request is sent to ensure the server trusts you before making the actual POST request to get data. It's the pre-flight that's failing. Most likely because the receiving server is not configured for cross domain requests, and doesn't send CORS headers back in the response. You need to verify with the API documentation to ensure that you can call it from client-side JS. – Rory McCrossan Nov 27 '19 at 09:07
  • You are using method:'POST' , kindly remove that. – Prabhjot Singh Kainth Nov 27 '19 at 09:08
  • 1
    Indeed I get a error message in the browser console `Access to XMLHttpRequest at 'http://link_of_web_service' from origin 'http://localhost:8084' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I will see again the documentation.. thanks for the info! – yaylitzis Nov 27 '19 at 09:14
  • 1
    @PrabhjotSinghKainth so that it defaults to a 'GET' request? How would that help anyone? – freedomn-m Nov 27 '19 at 09:24
  • 1
    @yaylitzis in which case the web service you're calling doesn't support CORS and therefore cannot be called from client-side JS. See the duplicate for more information about this. The workaround you will have to use is to make the API call from the server side instead. – Rory McCrossan Nov 27 '19 at 09:38
  • @RoryMcCrossan Thanks a lot! I will search it! – yaylitzis Nov 27 '19 at 09:52

0 Answers0