Asked  11 Months ago    Answers:  5   Viewed   9 times

I am using ionic framework and angularjs I use chrome for viewing my logs but here i am doing a login page I am trying to post the user entered data to serve but i am getting this error like .

 OPTIONS http://aflaree.com/qrcodeservice/Service1.svc/login 

and this one is next error XMLHttpRequest cannot load http://aflaree.com/qrcodeservice/Service1.svc/login Response for preflight has invalid HTTP status code 405 after reading some blog i figure there is a CORS extention from from which allows ajax request i tried that also but i am not able to find why this two error is appearing. here is my code

https://plnkr.co/edit/Dz0aFsLqoQcnCxht00z3?p=preview

my code work fine in device but I am getting error in chrome if any one knows why please help me

 Answers

5

CORS actually specifies that two requests should be made to the server on an AJAX call (if certain conditions apply, like sending custom headers).

The first request (the one with the OPTIONS method) is called pre-flight and is used to check if it's safe to send the full request to the server. The response from the server should contain a valid Access-Control-Allow-Origin header containing the URL of the client or *.

Your server (and not the client) is the one that needs to support CORS. It seems you are using .Net for it, so you may want to take a look here on how configure IIS.

You can read more about CORS here.

Saturday, July 3, 2021
 
SJain
 
1

This works :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.factory('chats', function($http){
      var chats = [];

      var _loading = $http.get('http://swapi.co/api/people').then(function(res){
        console.log(res.data.results);
        chats = res.data.results;
      });

      return {
        loading: _loading,
        all: function(){
          return chats;
        }
      };
    });

    myApp.controller('ChatsCtrl', function($scope, chats){
      $scope.chats = [];
      chats.loading.then(function(){
        $scope.chats = chats.all();
      });

    });


  </script>
</head>
<body ng-app="myApp">
  <div ng-controller="ChatsCtrl">
    <ul>
      <li ng-repeat="chat in chats">{{chat.name}}</li>
    </ul>
  </div>
</body>
</html>
Thursday, April 1, 2021
 
Ticksy
 
2

It looks like you are trying to make a cross domain AJAX call. For this to work your remote server API must support CORS. The pre-flight request is a special request that the browser sends using the OPTIONS verb prior to making the actual POST request:

OPTIONS http://blah-blah-blah

The server must respond with a normal 200 status code and include the proper CORS headers indicating which domains are allowed to make requests to it. Only after that the actual POST request will be sent.

The problem with your API is that the endpoint returned 405 Not Allowed status code to this OPTIONS request. So you will need to fix your API so that it supports the OPTIONS verb.

Friday, August 6, 2021
 
Rahul
 
3

@Rakeschand you were right and it was the issue of cors

Cors

I installed Cors in my project using nu-get command line

Install-Package Microsoft.AspNet.WebApi.Cors

and added the follwoing code in WebApiConfig.cs file from App_Start folder.

var enableCorsAttribute = new EnableCorsAttribute("*",
                                               "Origin, Content-Type, Accept",
                                               "GET, PUT, POST, DELETE, OPTIONS");
config.EnableCors(enableCorsAttribute);

and removed the following from the web config

   <remove name="X-Powered-By" />
                    <add name="Access-Control-Allow-Origin" value="*" />
                    <add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
                    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />

$http started working just like the $.ajax was working

but these things left me with some confusion. I would be great full if anyone can elaborate

  1. why the $.ajax was working and $http was not working
  2. I did the same thing by cors the I had done in web.config then why did cors worked but web.config didn't?
Tuesday, August 10, 2021
 
job
 
job
1

Yes, custom cordova plugins are painful because the official docs are not so great.

First of all we need to understand a custom plugin folder structure.

  1. wrapper - Name you want to give to your plugin
  2. src - folder where your source code goes
  3. android - since you are looking for android, an android folder is required
  4. www - it contains the javascript functions that calls the java code.(using cordova)
  5. plugin.xml - the very heart of the plugin, this files configures the plugin (adding permissions, copying files to platforms etc)

In your android folder create a CustomPlugin.java file.

package com.example.myplugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

public class CustomPlugin extends CordovaPlugin {

   @Override
   public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if ("beep".equals(action)) {
        // print your log here... 
        callbackContext.success();
        return true;
    }
    return false;  // Returning false results in a "MethodNotFound" error.
    }
 }

Now we need to build a interface between javascript and java code.

Cordova provides a simple function for this.

exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]); 

create a MycustomPlugin.js file in www folder.

cordova.exec( successCallback,  ErrorCallBack, "service","action", []);

It is worth to know that,

service -> Name of the java class

action -> action we want to call ( in this case "beep" see above code)

Your MycustomPlugin.js file should look like this:

var MyPlugin = {
  PrintLog: function (successCallback, errorCallback, action) {
    cordova.exec(
            successCallback, // success callback function
            errorCallback, // error callback function
            'CustomPlugin', // mapped to our native Java class called
            action, // with this action name , in this case 'beep'
            []  )// arguments, if needed
  }
}
module.exports = MyPlugin;

Lastly you need to configure your plugin.xml file

 <?xml version="1.0" encoding="utf-8"?>
    <plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
            id="com.example.plugin"
            version="0.0.1">        
      <name>Cordova Plugin</name> 

      <engines>
        <engine name="cordova" version=">=3.4.0"/>
      </engines> 

      <js-module src="www/MycustomPlugin.js" name="CustomPlugin">
        <clobbers target="window.MycustomPlugin" />
      </js-module>    
    <platform name="android">

        <config-file target="res/xml/config.xml" parent="/*">
           <feature name="CustomPlugin">
              <param name="android-package" value="com.example.myplugin.CustomPlugin"/>
           </feature>
        </config-file>

       <source-file src="src/android/CustomPlugin.java" target-dir="src/com/example/myplugin"/>     

   </platform>
</plugin>

now add this plugin to your project. myApp (the one you created) using cordova plugin add /path/to/your/custom/plugin

And in $ionicPlatform.ready function call your java code from javascript

   window.MycustomPlugin.PrintLog(function(res){
     //success
   }, function(err){
        //error
   }, "beep")
Sunday, September 5, 2021
 
Jon
 
Jon
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share