Having issues getting refresh_token in browser. Can't read XML Response - reactjs

I’m mainly a front end guy, and I’m having some issues getting data back from an api call. I think I just don’t understand something properly, so it’s proving to be massively frustrating. I wonder if anyone can offer some input.
I make the call like this:
var config = {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/xml',
},
proxy: {
host: '127.0.0.1',
port: 3000
}
};
axios
.post(
`https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&code=${authCode}`,
config
)
.then(res => {
console.log(`statusCode: ${res.statusCode}`);
console.log('Result:', res);
})
.catch(error => {
console.error('Error:', error);
});
Then the response I get is this:
Access to XMLHttpRequest at 'https://login.salesforce.com/services/oauth2/token?
grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLINET_ID&client_secret=CLIENT_SECRET&code=AUTH_CODE'
from origin 'http://localhost:3000' 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.
and this:
POST https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=https://localhost:3000/callback/&client_id=3[ID]&client_secret=[SECRET]&code=[CODE] 400 (Bad Request)
But if I put this link in my browser: https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLINET_ID&client_secret=CLIENT_SECRET&code=AUTH_CODE I can see it’s an XML file with all the info I need. So why can’t I just get that info in my response?
This is what I see when I paste the link in my browser:
<OAuth>
<access_token>
{Token}
</access_token>
<refresh_token>
{Token}
</refresh_token>
<signature>{Signature}</signature>
<scope>refresh_token api full</scope>
<id_token>
{Token}
</id_token>
<instance_url>https://um5.salesforce.com</instance_url>
<id>
{ID}</id>
<token_type>Bearer</token_type>
<issued_at>1558167449074</issued_at>
</OAuth>
I've obviously taken out the actual tokens. This is the info I need.
Please can someone assist me in actually accessing that XML info on the front end? Id I do the request on Postman, I get exactly what I need.

I fixed it by using this code on a Node server and seemed to be getting the response I needed:
var request = require('request');
var options = {
url: `https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLIENT_ID.&client_secret=CLIENT_SECRET&code=${token}`
};
function callback(error, response, body) {
if (!error) {
console.log('Body: ', body);
} else {
console.log('Error: ', error);
}
}
I hope this helps someone. Salesforce documentation is very disjointed and complicated.

Related

How do i enable cors policy / or request in react js with no access to the API?

Im using RapidApi to make som simple calls for fetching country data using axios. The API is paged in that the next response will have the URL for the next request. So basically i don't even have the URLs.
Problem i get the error which i have seen all over stack overflow about cors policy
Access to XMLHttpRequest at 'https://api.hybridgfx.com/api/list-countries-states-cities?page=2' from origin 'http://localhost:3002' 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 tried adding the line "access-control-allow-origin": "*" but that doesn't work and i still get the same error. When i click on the URL or just run it directly on the browser i get a bunch of data but when it is called in the code it blows up . Please help.
const fetchNextResults = async (url: string): Promise<FetchResponse> => {
const options = {
method: "GET",
url: url,
headers: {
"X-RapidAPI-Key": MyKey,
"X-RapidAPI-Host": "countries-states-cities-dataset.p.rapidapi.com",
"access-control-allow-origin": "*",
},
};
const res: FetchResponse = await axios
.request(options)
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
console.error(error);
});
return res;
};
You can send a request throw the CORS proxy.
List of proxies.
url: <proxy url>/<my url>
Or create your own.

CORS errors on Axios Graphql query

I'm trying to use react-axios to query a graphql endpoint but I'm encountering a problem with CORS.
Access to XMLHttpRequest at 'https://rickandmortyapi.com/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here it is my setup:
const characterQuery = `{
characters(page: 2, filter: { name: "rick" }) {
info {
count
}
results {
name
status
species
gender
image
}
}
}`
const axiosInstance = axios.create({
data: characterQuery,
headers: {"Access-Control-Allow-Origin": "*"}
})
<AxiosProvider instance={axiosInstance}>
<Post url="https://rickandmortyapi.com/graphql">
{(response: any) => {
console.log(response);
}}
</Post>
</AxiosProvider>
Can someone help me? Thanks
CORS is a pain, always, the problem is that the header you pass is the one the server should give you.
You can't force the server to pass the header if they don't already, that the whole point of this protection, avoiding hacker pretending to be other ppl websites.
So the API you are trying to reach must have the CORS header or it will not work
You can play around with fetch see if you have better luck than axios.
Fetch provide some amount of control over your CORS settings, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://rickandmortyapi.com/graphql', {
method: 'POST',
mode: 'cors',
headers: { "content-type": "application/json" },
body: JSON.stringify({
query: `{
character(id: 1) {
name
}
}`
})
})
This request work with fetch for me, uppon testing, if the content-type was not set to application/json the server failed with error 500 instead of showing a 400 bad request
Edit again, it works with axios too, are you sure you get a CORS error ?

.. from origin .. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I'm fairly new to making API requests. I'm am trying to set up an incoming slack webhook using a simple axios post request from my React project, however I keep receiving the CORS policy error. The request works perfectly in insomnia.
I'm using ngrok to expose my web server running on my local machine to the internet (I assumed this would correct the issue.) So I'm making the request from https://...ngrok.io, however I'm still receiving 'Status Code: 400' in my network tab along with the error above.
axios({
method: "post",
url:
"https://hooks.slack.com/services/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",
headers: { "Content-type": "application/json" },
data: { text: "Hello, World!" },
}).then(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
};
There are similar errors on stackoverflow, but none fix my error. I'd really like to understand why this is happening so any advice would be appreciated.
Fixed it, for those having the same issue:
What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

I can't perform a request from ReactJS. The header can not be written correctly

axios.get('http://localhost:8080/omp/patients', { headers: {authorization: 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
In network I have the field: "Access-Control-Request-Headers: authorization" but no field "authorization: token"
You will need to set the Authorization header correctly, as in the comment above.
For your reply about CORS Policy:
You will need to learn about CORS, but essentially Chrome and other browsers halt network requests if they do not have proper CORS headers set upon response. A preflight is an initial request that is sent to the same URL to learn whether the URL will support CORS, before sending the actual request. It looks like the server doesn't understand CORS preflights or isn't configured properly.
You have a couple options:
If you have access to the server configuration or code (such as a Laravel or NodeJS server), install a CORS plugin.
If you are the only user using this, you can install CORS browser extensions for Chrome or Firefox or whatever.
Change your code to this:
axios.get('http://localhost:8080/omp/patients', { headers: { "Authorization": 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
Also in you app.js/index.js where ever you are running your server import/require cors module and do like this:
let cors = require('cors');
app.use(cors());
Hope this helps!

React JS - No 'Access-Control-Allow-Origin' header is present on the requested resource. Cross Origin Resource Error

Im making an API call(Running on another domain) using Fetch in a React Web app. I am getting the error Following error.
Access to fetch at
'--------API URL---------' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I have also read several answers on StackOverflow about the same issue, titled "Access-Control-Allow-Origin" but still couldn't figure out how to solve this. I don't want to use an extension IN Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.
my code looks like this.
{
return fetch('-----------API URL--------',
{ method:'GET',
mode: 'cors',
headers:{
'Access-Control-Allow-Origin':'*'
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.ALLORDERSRX);
this.setState({
isLoading: false,
dataSource: responseJson.ALLORDERSRX,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = 'https://api.liveconnect.in/backend/web/erpsync/get-all-orders?data=dbCode=UAT04M%7Cidx=100%7CuserId=6214%7Cres_format=1'; // site that doesn’t send Access-Control-*
fetch(proxyurl + url).then((resp) => resp.json())
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
found from here :No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
The probable reason why you're getting the CORS error message is that the API has a different origin than where you are doing the requests from, so you need to tell the API that it is okay to accept requests from other origins (it's better to specify from what other origins instead of saying that from everyone).
I had a similar issue, I tried changing the header from the part of the front-end from where I was doing the calls and then also tried changing the controller but what worked for me was changing the Start.cs file of the API project and add the following... (I recommend trying it first in localhost and then deploying the changes where you actually have the API)
public class Startup
{
private readonly string _MyCors = "MyCors";
.
.
.
public void ConfigureServices(...)
{
.
.
.
//Under your services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(name: _MyCors, builder =>
{
//for when you're running on localhost
builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost")
.AllowAnyHeader().AllowAnyMethod();
//builder.WithOrigins("url from where you're trying to do the requests") this should be specified to get it working on other environments
});
});
}
public void Configure(.....)
{
//before the app.UseAuthorization & app.UseEndpoints
app.UseCors(_MyCors);
}
}

Resources