0

I use this code in my html page to post json data to server using toggle switch ( depending on the value of toggle switch)

  $('#ledToggle').change(function () {
      var ledState = $(this).prop('checked');
      var body = {
          //Key: "1",
          LedState: ledState
      };
      console.log(body);
      body1 = JSON.stringify(body);
      console.log(body1);

      return $.ajax({
          type: "POST",
          url: "http://localhost:8060/api/led",
          data: JSON.stringify(body),
          dataType: "json",
          contentType: "application/json"
      });

But it always give me response 405 "Method not allowed" in Mozilla and "XMLHttpRequest cannot load http://localhost:8060/api/led. Response for preflight has invalid HTTP status code 405" in Chrome.

And when I uses Postman or fiddler to post it posts normally.

MBS
  • 673
  • 2
  • 16
  • 48
  • Where is your html page running from? Do you have it on localhost? – Dr Rob Lang Jun 21 '16 at 09:44
  • It runs on the same PC that runs the API – MBS Jun 21 '16 at 09:47
  • What is the URL of the original html page? Can you paste it in here? – Dr Rob Lang Jun 21 '16 at 09:48
  • It's a cross origin request with a content-type you can't generate with a form. It gets preflighted. The server is 405ing because it doesn't support OPTION requests. No need to keep asking questions to figure out what is going on. The duplicate question explains what is going on. – Quentin Jun 21 '16 at 09:49
  • I didn't publish it. file:///C:/projects/temp/IOT.Web/IOT.Web/LED.html – MBS Jun 21 '16 at 09:50
  • @Quentin thank you I will see if the answers help me or not – MBS Jun 21 '16 at 09:51
  • @bilal For a page to run ajax, it needs to be hosted. Browsers prevent `file://` from doing ajax for security reasons. Once it is hosted then you might still get a problem with CORS as @Quentin suggests. Please update your question with the URL in it as others might have the same problem. – Dr Rob Lang Jun 21 '16 at 09:53
  • So if I publish it, it will work? – MBS Jun 21 '16 at 09:57
  • @Quentin I figured out the problem but I didn't found a solution – MBS Jun 21 '16 at 10:06
  • The solution is to either (a) Not make a cross origin request (b) Not format the request as Ajax or (c) Configure the server to respond correctly to the OPTIONS request with permission for the foreign origin to make the request – Quentin Jun 21 '16 at 10:06
  • Thank you for helping e to understand the problem. I use the solution in this question to enable cors in API. http://stackoverflow.com/questions/29024313/asp-net-webapi2-enable-cors-not-working-with-aspnet-webapi-cors-5-2-3 – MBS Jun 21 '16 at 11:22

0 Answers0