Access to XMLHttpRequest at <url> has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers - ionic-framework

Im trying to consume TomTom maps api to get the location .
My function :
getLocationAddress(lat: number, lon: number) {
const url = `${baseUrl}search/${versionNumber}/reverseGeocode/${lat},${lon}.json/?key=${apiKey}`;
const headers = new HttpHeaders({
"Content-type": "application/json",
"Access-Control-Allow-Methods": "GET,OPTIONS,POST",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Authorization,Content-Type",
});
const observable = this.http.get(url, { headers: headers });
return observable;
}
The url is correct and i have provided the headers as above . I cant get past this error:
Access to XMLHttpRequest at <url> has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response
TomTom is a 3rd party api server . The is routed to the correct location and i can see the response from the server on the browser when pasting the link in a new window

Based on the error message it appears your headers are misconfigured, specifically the "authorization" header attribute.
You may want to use their SDK and/or JS libraries, at it will set the headers for you.
You need to provide an API key, otherwise CORS policy will reject the requests, as shown in their examples https://developer.tomtom.com/maps-sdk-web-js/functional-examples#examples,code,vector-map.html

Related

Is the LinkedIn REST API accessible client side?

I'm building a React app and Express API with a "Sign in with LinkedIn" feature. I've got my OAuth sorted, so I have an access token now but I keep getting a CORS issue when I try using it to fetch data. Can I make REST API requests directly from my React app (client side)? Or do I need to proxy every request through my own Express server / API?
useEffect(() => {
// get linkedin data
fetch(`https://api.linkedin.com/v2/me`, {
method: 'get',
mode: 'cors',
headers: {
'Connection': 'Keep-Alive',
'Authorization': `Bearer ${accessToken}`
},
}).then(response => response.json()).then(function(data) {
console.log(data);
});
}, []);
Access to fetch at 'https://api.linkedin.com/v2/me' 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.

Yammer REST API - How can I fetch data from a different origin (CORS)?

I have created a Yammer app in "My Apps" and have set my Javascript Origin to my local development URL:
http://localhost:3000
In my React app, I am trying to use the Fetch API to get some data. For example:
const url = 'https://www.yammer.com/api/v1/messages/following.json';
const options = {
method: 'GET',
mode: 'cors',
headers: {
'Authorization': `Bearer ${process.env.REACT_APP_YAMMER_ACCESS_TOKEN}`,
}
};
fetch(url, options).then(function(response) {
console.log(response);
return response.json();
}).then(function(json) {
console.log(json);
});
I get a CORS error:
Access to fetch at
'https://www.yammer.com/api/v1/messages/following.json' 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 my Javascript Origin set in the Yammer dashboard and I have the mode set to CORS in my fetch request. What am I missing?
I got it working with a different URL:
const url = 'https://api.yammer.com/api/v1/messages.json';
I haven't seen this documented anywhere but I saw someone reference it here on another StackOverflow post.

Yammer autocomplete: No request after successful CORS preflight

Ok, so I've been struggling for a while now...
I'm trying to make a GET request to this URL:
https://api.yammer.com/api/v1/autocomplete/ranked?prefix=oper&models=group:5,user:5,topic:5,
And I see the preflight succeeding:
The problem is that no GET request is made after the preflight. I'm using axios and doing something like:
axios({
"https://api.yammer.com/api/v1/autocomplete/ranked?prefix=oper&models=group:5,user:5,topic:5",
"get",
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
}
})
Why do you guys think the actual request is not being sent?
Turned out to be a CORS problem.
Seems like Yammer changed something on their side and broke that endpoint. Touché
I had to solve it proxying my requests to that endpoint to my server and return the response from there.

HTTP authorization headers not send with codeigniter api in ionic 2

In API they call without Authorization is fine.
How to set header for it?
"thanks"
let headers: Headers = new Headers({ 'Authorization': token, 'Content-Type': 'application/json; charset=UTF-8' });`
let options: RequestOptions = new RequestOptions({headers: headers});
let params: URLSearchParams = new URLSearchParams();
params.append('latitude', '23.259933');
params.append('longitude', '77.412615');
params.append('nearby', '5');
return this.http.post(baseUrl, params, options)
.map(
(response: Response)=>{
return response;
}
)
Chrome console:
Response for preflight has invalid HTTP status code 404
This happens because the browser sends the headers of your request to the server before sending the actual request (what is called preflight) so as to verify your request complies with the CORS policy that is defined in the server's configuration.
So what you need to do is double check that the server you are contacting is configured properly to accept the request as you make it.
Make sure that your backend server is accepting not only the POST request but also an OPTIONS request for the same endpoint url. The OPTIONS request should just return with the success 200 code.
On that server you probably have something like "when a user hits endpoint /abc with request type POST, then return some data". You also need something that says "when a user hits endpoint /abc with request type OPTIONS return 200 OK"
If all else fails you could try using this plugin in your browser, but keep in mind this will help only continuing development and is a band-aid solution that won't work in production of course.

Error 401 (Unauthorized) When making REST calls using Axios with JWT headers included

I'm developing a small react node application with JWT passport for authentication. I've tested all the endpoint through postman(by passing token with authorization header) and they are working properly.
This is the call im making from the front-end
export const getUsersDetails=()=>{
console.log( localStorage.getItem('jwtToken'));
return (dispatch) => {
return axios.get('http://localhost:3030/users',
{ headers: { 'Authorization': localStorage.getItem('jwtToken') } }
).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
I have enable CORS by using the the CORS module. this is the how the network calls looks like from the browser
the authorization header looks like
authorization:[object Object], eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Should this be like authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Is this the reason why im facing this issue? How to overcome this?
I was able to solve a similar issue on a MERN stack, by configuring axios globally in the react application, by adding Bearer and one space, in front of the token that is assigned globally.
axios.defaults.headers.common['Authorization'] =Bearer ${token};
initially, it was without Bearer and i kept getting a 401 status code.
axios.defaults.headers.common['Authorization'] = token;
When you want authorization in your app, it depends on how you have done your back end. If everything is ok trough postman, show how your headers in postman look when you have tasted. I use xsrf token and here is how my request header look:
{headers:
{"Access-Control-Allow-Headers" : "*",
"X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN')}
}
Maybe you should just put "Access-Control-Allow-Headers" : "*"