Is the LinkedIn REST API accessible client side? - rest

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.

Related

Intercept each http request globally in flutter http package

I have many API calls to the server, in many of them if I get a 401 response then I should forward the user to the login screen to refresh the token that I used for authorization.
http.post(
URL,
body: jsonEncode(loginHttpBody),)
.then((response) {
if (response.statusCode == 401) {
Navigator.pushNamed(context, LoginScreen.id);
}
});
I need a way to make a global interceptor to check if any of the HTTP requests have 401 status to forward the user to log in screen, not writing this code in all of my HTTP requests.
The package that I use for my HTTP request is http

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

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

Can't resolve Dropbox.com redirects with Axios or D3-fetch

I'm trying to fetch data in the browser from a Dropbox link: https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1
Using Axios this works in Node:
axios.get('https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1').then(x => {
console.log('Received correctly')
console.log(x.data);
}).catch(error => {
console.log('Error', error.message);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
}
console.log(error)
});
https://runkit.com/stevebennett/5dc21d04bbc625001a38699b
However it doesn't work in the browser (click the "Console" tab):
https://codepen.io/stevebennett/pen/QWWmaBy
I just get a generic "Network Error". I see the 301 Redirect being retrieved, which seems perfectly normal, but for some reason, it is not followed.
Exactly the same happens with D3: "NetworkError when attempting to fetch resource."
https://codepen.io/stevebennett/pen/KKKoZYN
What is going on?
This appears to be failing because of the CORS policy. Trying this with XMLHttpRequest directly fails with:
Access to XMLHttpRequest at 'https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1' from origin '...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CORS isn't allowed on www.dropbox.com itself.

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.

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" : "*"