简体   繁体   中英

How to call web API with GET method basic authentication into jquery() in javascript

Hello I am using this method to read this api it giving CORS error. I have added CORS plugin with chrome then also it is not coming. Please let me know how to solve these to error.

text:

 function NoCors() {
        debugger;
        var uName = "*****";
        var passwrd = "*****";
        document.write("Enter1");
        var url = 'http://219.90.67.163:8207/api/Info/getgismeterdata'
        $.ajax({
            type: 'GET',
            url: url,
            crossDomain: true,
            //Access-Control-Allow-Credentials: true,
            contentType: 'json',
            datatype: "application/json",
            headers: {
                "Authorization": "Basic QXBpVXNlcjpBcGlQYXNz",
            },

            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', "Basic " + btoa(uName + ":" + passwrd));
            },
            success: function (data) {
                debugger;
                console.log("data")
                //Success block 
            },
            error: function (xhr, ajaxOptions, throwError) {
                //Error block 
            },
        });
    }

error in console: 1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed) 2. Access to XMLHttpRequest at ' http://219.90.67.163:8207/api/Info/getgismeterdata ' from origin ' http://localhost:50362 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Before sending the GET request to server, browser automatically send and preflight OPTIONS request, and your server doesn't allow this method. You need to enable OPTIONS method support in your server side (219.90.67.163)

  1. Are you use Bearer Token Authentication? requst headers try this

    headers: { "Authorization": "Bearer QXBpVXNlcjpBcGlQYXNz", },

  2. You must setting CORS in Web API

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

The CORS plugin you are using only works for Simple Requests .

Since you are setting an Authorization header you are making a Preflighted Request which your plugin cannot handle.

You need a different approach to handling the Same Origin Policy. Ideally, that would be proper support for CORS on the server you are making the HTTP request to but some other options are listed at the end of this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM