function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Hemant Gulati 4Hemant Gulati 4 

XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am calling a rest API from javascript from third party appplication outside salesforce and  getting this issue:-

XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400.


My Code:- 
$.ajax({
                    type: 'GET',
                    url: 'https://login.salesforce.com/services/oauth2/token',
                    contentType: 'application/json',
                    dataType: 'json',
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader('grant_type','password'),
                        xhr.setRequestHeader('client_id',  'CLIENT_ID'),
                        xhr.setRequestHeader('client_secret', 'LIENT_SECRET'),
                        xhr.setRequestHeader('username', 'Username'),
                        xhr.setRequestHeader('password', "Password+securityToken")
                    },
                    success: function(response) {
                        console.log('Successfully retrieved ' + response);
                        //Other logic here
                    },
                    error: function(response) {
                        console.log('Failed ' + response.status + ' ' + response.statusText);
                        //Other logic here
                    }
                });


I have made an Connected app adn provide access to that user in Profile settings.

Here are some of my questions:-
1. The callback url in connected app can be http://localhost or should be a proper server URL.
2. Do i need to add http://localhost(server URL) in CORS and REMOTE settings
3. Server URL should be HTTPS (secured)

Please help me in this.

Thanks in advance!
4. I mentioned my error above , please help me in resolving it.
                

 
Best Answer chosen by Hemant Gulati 4
VinodKRVinodKR
Hi Hemant,

Try this it worked for me.

<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        loginsf(function(data) { 
           $.ajax({
              type: "GET",
              contentType: 'application/json',
              url:'https://sfdc-cors.herokuapp.com/services/apexrest/prefix_if_exsists_for your_org_else_dont_add/RestAPI/',  
              cache :false,
                headers: {'Authorization': 'Bearer '+data},
              dataType: 'json',
              success: function (data) {
                  
              },
              error : function(jqXHR, textStatus, errorThrown) {
                  console.log('Error: '+jqXHR.status);
                  console.log('textStatus: '+textStatus)
                 } 
           });
        });    
    });
});

function loginsf(fn){
     $.ajax({
            type: 'POST',
            crossOrigin: true,
            url: 'https://sfdc-cors.herokuapp.com/services/oauth2/token',
            dataType: 'json',
            cache :false,
            data : {"grant_type":"password","client_id":"add_your_client_id", "client_secret":"your_client_secret","username":"Your_username","password":"your_password_and secritytoken"},
            success : function (data) {
             fn(data.access_token);
            },
            error : function (data, errorThrown,status) {

            }
    });
  }
    
</script>
</head>
<body>

<div id="div1"><h2>jQuery AJAX test</h2></div>

<button>Get External Content</button>

</body>
</html>



Thanks,

Have a great day ahead,Let the Force be with you!
Please mark this as best answer if it helps you.
 

All Answers

VinodKRVinodKR
Hi Hemant,

For the issue you are getting first you need to add this:

xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Range, Content-Disposition, Content-Description');

and later you need to use the below link suggested if you need to connect to salesforce  from local javascript or third party appplication,for callback url you could add localhost.

Link - http://www.jamesward.com/2014/06/23/cross-origin-resource-sharing-cors-for-salesforce-com

Hope this answers your question,if not me know?

Thanks,

Have a great day ahead,Let the Force be with you!
Please mark this as best answer if it helps you.
 
 
Hemant Gulati 4Hemant Gulati 4
After adding 
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Range, Content-Disposition, Content-Description');

also , nothing is changed,

Please answer to the questions i mentioned inthe original post.

Thanks,
VinodKRVinodKR
Hi Hemant,

Try this code it worked for me locally,any question on domain name check the link above.

<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
                    type: 'POST',
                    crossOrigin: true,
                    url: 'https://sfdc-cors.herokuapp.com/services/oauth2/token',
                    dataType: 'json',
                    cache :false,
                    data : {"grant_type":"password","client_id":"add_your_client_id", "client_secret":"your_client_secret","username":"Your_username","password":"your_password_and secritytoken"},
                    success : function (data) {
                        alert(data.access_token);
                    },
                    error : function (data, errorThrown,status) {

                    }
                });
    });
});
</script>
</head>
<body>

<div id="div1"><h2>jQuery AJAX test</h2></div>

<button>Get External Content</button>

</body>
</html>


 
Hemant Gulati 4Hemant Gulati 4
Thanks for the information. It helps me to get access token and instance URL. Thanks again.

I have one more question , please help me in this too.

I made a custom Rest service:-

@RestResource(urlMapping='/RestAPI/*')
global with sharing class testRestApi {

@HttpGet    
  global static String createNewExpense() {
     
     Expense__c exp = new Expense__c();
     exp.Name = 'BreakfastTest';
     exp.Amount__c = 30;
     exp.Client__c = 'ABC';
     insert exp;
     
    return 'Expense Submitted';
  }
}


What will be the ajax call to get this service from javascript? Is the below code Correct to get this done?

//GET METHOD
                        $.ajax({
                                type: 'GET',
                                crossOrigin: true,
                                url: "https://sfdc-cors.herokuapp.com/services/apexrest/RestAPI",
                                headers: {
                                    "authorization": "OAuth  ACCESSTOKEN"
                                },
                                success : function (data) {
                                    alert(data);
                                },
                                error : function (data, errorThrown,status) {
                                    
                                }
                            });


Please reply.

Thanks,
VinodKRVinodKR
Hi Hemant,

Try this it worked for me.

<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        loginsf(function(data) { 
           $.ajax({
              type: "GET",
              contentType: 'application/json',
              url:'https://sfdc-cors.herokuapp.com/services/apexrest/prefix_if_exsists_for your_org_else_dont_add/RestAPI/',  
              cache :false,
                headers: {'Authorization': 'Bearer '+data},
              dataType: 'json',
              success: function (data) {
                  
              },
              error : function(jqXHR, textStatus, errorThrown) {
                  console.log('Error: '+jqXHR.status);
                  console.log('textStatus: '+textStatus)
                 } 
           });
        });    
    });
});

function loginsf(fn){
     $.ajax({
            type: 'POST',
            crossOrigin: true,
            url: 'https://sfdc-cors.herokuapp.com/services/oauth2/token',
            dataType: 'json',
            cache :false,
            data : {"grant_type":"password","client_id":"add_your_client_id", "client_secret":"your_client_secret","username":"Your_username","password":"your_password_and secritytoken"},
            success : function (data) {
             fn(data.access_token);
            },
            error : function (data, errorThrown,status) {

            }
    });
  }
    
</script>
</head>
<body>

<div id="div1"><h2>jQuery AJAX test</h2></div>

<button>Get External Content</button>

</body>
</html>



Thanks,

Have a great day ahead,Let the Force be with you!
Please mark this as best answer if it helps you.
 
This was selected as the best answer
Hemant Gulati 4Hemant Gulati 4
Thanks for your help Vinod. I really appreciate your help.

If possible just send me one example of POST data to insert a new record into salesforce after aurthorization.

 
VinodKRVinodKR
Hi Hemat,

Try this:

Here 'formParams' is the data in json format this is a hard coded json format but you can do it dynamically also.

var formParams = '{'+
        '"Name": "Rest Api ",'+
        '"ProductId":'+
          '[{'+
              '"Id":"id"'+
          '}]'+
       '}';

loginsf(function(data) { 
  $.ajax({
        type: "POST",
        contentType: 'application/json',
        url:'https://sfdc-cors.herokuapp.com/services/apexrest/RestAPI',  
        data:formParams,
        cache :false,
          headers: {'Authorization': 'Bearer '+data},
        dataType: 'json',
      success: function (data) {
        
      },
      error : function(jqXHR, textStatus, errorThrown) {
      
      } 
    });
   });    
  }

Thanks,
Hemant Gulati 4Hemant Gulati 4
Thanks again.

Ihave one more question:-

I have a FILE field (Custom) in knowledge article , and i can able to get the response of knowledge article file "Attachments__Body__s" value as a URL through rest API.
eg:- Attachments__Body__s: "/services/data/v34.0/sobjects/Test_Knowledge__kav/ka01a000000MEc0AAG/Attachments__Body__s"

How can i open that file ? means what will be the URl for that particular file.

OR if we haveiing any attachment to any of the objects record in salesforce and if we are fetching that attachment through REST API, how can we open that attachment in the application where we are calling that rest API service.

Plesae help me in this.

Thanks,
 
Hemant Gulati 4Hemant Gulati 4
I just need to know how can an attchment of a record in any of the object or a file filed value for an KNowledge article can be open in third party application.

Thanks,
VinodKRVinodKR
Hi Hemant,

In your third party application you need to typecast the Attached file from blob to string.

Thanks,
Hemant Gulati 4Hemant Gulati 4
Vinod,

I need to use rest api to get the attachment from salesforce adn shown on thrid party application,

Please send methe code for the same.
VinodKRVinodKR
Hi Hemant,

For that i need to know which is the thrid party used by you.

Thanks,
Hemant Gulati 4Hemant Gulati 4
I want to get an attachment(png,jpeg,xls,doc,pdf,etc) of a record(in salesforce) through REST API using javascript in my application.
Hemant Gulati 4Hemant Gulati 4
Hi Vinod,

I like to get the Public URL of an attachment in a record, so that i'll access that attachment from outside salesforce like (in asp.et web application, or java application or through javascript.), using Rest API.

 
YASH AGARWAL 6YASH AGARWAL 6

I am getting bad request 400 error for this .

Can any one help

Awais IlyasAwais Ilyas
I am getting this error in console
POST https://sfdc-cors.herokuapp.com/services/oauth2/token 400 (Bad Request)

Can any one help
 
Mohit NagrathMohit Nagrath
I am getting this error  while trying to use the salesforce login for my web application.this error is shown on invoking the initial request for the consent page when calling this endpoint from javascript.I tried adding the origin url to remote site settings and cors header.
also have the headers in place.
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); //also tried https://xyz.com
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    xhr.setRequestHeader('Access-Control-Allow-Headers', ' Origin, Content-Type, X-Auth-Token');
   xhr.setRequestHeader("Access-Control-Allow-Credentials","true");

Request URL:
https://login.salesforce.com/services/oauth2/authorize/
Request Method:
OPTIONS
Status Code:
200 OK

-----------------------
Request Headers
Accept:*/*
Accept-Encoding:
gzip, deflate, sdch, br
Accept-Language:
en-US,en;q=0.8
Access-Control-Request-Headers:
access-control-allow-headers, access-control-allow-methods, access-control-allow-origin, content-type
Access-Control-Request-Method:
POST
Connection:
keep-alive
Host:
login.salesforce.com
Origin:
https://xyz.com
Referer:
https://xyz.com/login
User-Agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36

tried using both get and post using plain text and application/json but still stuck with this error.The response does show a 200 OK but is empty with this error below in the js console.is it not possible to perform this call from javascript in salesforce? i  see the google sign in does allow this call to fetch the intitial token.
   
Error:XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/authorize/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'xxxxx' is therefore not allowed access.

any response would be highly appreciated.

Thanks
Hemant Gulati 4Hemant Gulati 4
Try using https://login.salesforce.com/services/oauth2/token with grant_type=password
Mohit NagrathMohit Nagrath
Hi Hemant i tried using that but it gives the following error.
<OAuth>
<error>unsupported_grant_type</error>
<error_description>grant type not supported</error_description>
</OAuth>

so to clarify its failing in the first step where i am trying to request the authorization code. is that not needed?
i use this url : 

https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=3MVG9rFJvQRVOvk5h49JookcZyNxIeL4WaGdOdhmS6PD73AUzIWrqlwcGGNCZyn0ZobQVLOiuCklTeEfCyD7.&redirect_uri=https%3A%2F%2Fwww.salesforce.com
 
note when i use the redirect uri of "salesforce.com" it redirects successfully with a code in the url response param,but when i use my own domain eg: https://xyz.com then i am getting different responses: sometimes 302 with a preflight error.Looks like i am missing something here?
Mohit NagrathMohit Nagrath
This is the error "Response for preflight is invalid (redirect)"
Response Header : 
with response code 302

 
silpa garikapatisilpa garikapati
Hi Vinod,

Please clearly explain how i done in my salesforce org of other third party xml file as you mentioned above.

Thanks
Akshay Chouhan 17Akshay Chouhan 17
CORS error while calling Salesforce Token API from JS AJAX

I tried calling the Salesforce Token api (https://test.salesforce.com/services/oauth2/token) using postman , and it is working fine. Now I tried calling the same API from my JS code using AJAX request, and it keeps giving me CORS error. I did the settings in CORS section, Remote Site Settings section of Salesforce setup page for allowing request from my domain etc. But nothing changes. After searching, it was suggested to use a proxy API. But I am not looking for proxy related solution. There must be some settings on Salesforce end to allow a ajax request. Following is the ajax request:


$.ajax({
type: "POST",
url: "https://test.salesforce.com/services/oauth2/token",
beforeSend: function(xhr) {
     xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
crossDomain: true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: { grant_type:"authorization_code", client_secret:"my client secret", client_id:"my client id", code:"authenication code", redirect_uri:"https://<some domain>.com/" },
success: function (response) {
   console.log(response);
},
error: function (a, b, c) {
   console.log("An error occurred."); return false;
} });


Plesae help me in this.

Thanks,
patricia wildpatricia wild
Access control is one of the most essential things for security purposes. Today it has become a big deal for everyone as almost everyone is leaving their home or workplace and entering other public places like malls, parks, railway stations, and many more. Suppose you want to secure your own business from any kind of danger. In that case, it is also essential to provide your own public place with safe access control systems (https://dicsan.com/access_control/access-control-miami/) that will help you get the access you want. The primary purpose of access control services in Miami is to ensure the safety of your own home or office by providing you with safe access control systems and also video monitoring.