How to GET to LinkedIn API? - reactjs

I am trying to retrieve user info from LinkedIn API, calling api.linkedin.com/me and sending token within axios. But I am getting 404 error - https://gyazo.com/b08b3eba1cbfd5809ede994b1af67fb5
I am able to get an access token from their API, but I stuck on getting user info
Here is a piece after I get a token I call api.linkedin.com/me like:
.then(function (response) {
axios.get('https://api.linkedin.com/me', {
headers: {
Authorization: 'Bearer ' + response.data.access_token
}
}).then(function (response) {
console.log(response)
})
})
.catch(error => {console.log(error)})
}
I need to be able to fetch data of the user, but I cannot make a valid request
Thank you in advance!

Changing the get URL to https://api.linkedin.com/v2/me should solve the problem.
I say this because https://api.linkedin.com/me redirects to a 404 page on linkedin, however, https://api.linkedin.com/v2/me returns a json response.

Related

Expressjs Server cannot handle Requests from the Outside

I have a ExpressJs Server with React Components. And the Server should handle Requests from Outside and one request should play a Song from the Spotify API when not currently playing.
app.post("/play", (req, res) => {
try {
// requesting to play uses query params
id = req.query.id;
currPlayingID = 0;
// get the currently playing song from the SPotify API
axios({
url: "https://api.spotify.com/v1/me/player/currently-playing",
method: "get",
headers: {
authorization: `Bearer ${access_token}`,
},
})
// set the currently Playing ID or to zero if nothing is playing
.then((response) => {
if (response.data !== null) {
currPlayingID = response.data.id;
} else {
currPlayingID = 0;
}
});
// only play the song if its not currently playing
if (id !== currPlayingID) {
// making a axios request to the Spotify API to play the Song with the ID
axios({
url: "https://api.spotify.com/v1/me/player/play/",
method: "put",
headers: {
authorization: `Bearer ${access_token}`,
},
data: {
uris: [`spotify:track:${id}`],
},
});
res.status(204);
}
} catch (error) {
res
.status(404)
.json({ message: "Couldn't get Info from Spotify API", error: error });
}
});
The Problem:
The Code works when I start the server on the device itself (so a local server on my Desktop PC), but when I start the Server on my RaspberryPI i cannot handle Requests to this endpoint /play. Yeah I updated all the IP Adresses, everywhere.
But the moer ointeresting part is using the React Client I get this error:
Failed to load resource: net::ERR_CONNECTION_REFUSED
Requesting with POSTMAN I get the following:
Mixed Content Error: The request has been blocked because it requested an insecure HTTP resource
And from a request using a python script I get on the server side:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 400".] {
code: 'ERR_UNHANDLED_REJECTION'
}
I have no clue how to fix each error and if it is one fix. Basically I found out it is a Problem with rejeccting requests from outside localhost, because with cURL on my ssh terminal it works.
I'm learning express, so I m not an expert, but I'm looking at your errors. I will suggest you try asyncHandler module. It handles asynchronous requests and exceptions.
I faced a similar issue because while I'm sending the API request via
Axios, my token is null/empty/wrong, so make sure your token is correct
this is my request format
axios({
method:"POST",
url:"https://graph.facebook.com/v13.0/"+phon_no_id+"/message?access_token="+token,
data:{
messaging_product:"whatsapp",
to:from,
text:{
body:"Hi.. I'm Prasath"
}
},
headers:{
"Content-Type":"application/json"
}
});

401 unauthorized browser alert after fetch call with bearer token in react

I have a get fetch request with header having Bearer token, getting 401 unauthorized error, even if the response status condition checked in the then statement,the browser is showing sign in alert box, can you please suggest how to avoid browser alert on 401 error
function call(url: string, req:RequestInit):Promise<Any>{[enter image description here][1]
req.headers = { Authorization: 'Bearer ' + idToken };
return fetch(url, req)
.then((response: Any) => {
if (response.status !== 200) {
// return to base url
return false;
} else {
return response;
}
})
}
for
Whether the prompt displays or not depends on WWW-Authenticate header that you receive in the response.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
Verify what are the conditions for it to appear in response (server-side) or if you can configure server not to send this header. If you cannot modify server itself, you can try to use a proxy.
Refer to How can I suppress the browser's authentication dialog?

How to fetch data from a REST API by using an API-Token

I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests. An API token is necessary, in order to access data via the Jira API. I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.
This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:
curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool
This is the React state hook for setting the data to the fetched data:
const [jiraTicket, setJiraTicket] = useState([]);
This is the fetch function for the API request (${} will be filled with user input):
function getJiraTicket() {
axios.get(`${username}:${apiToken}#Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
.then((res) => {
const data = res.data;
setJiraTicket(data);
})
}
The button inside the react component return should invoke the fetch function:
return(
<Container>
<Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
</Container>
);
This is the error I'm currently getting, because the authorization is not working the way I did it
(I replaced the provided username, API token etc. for this example):
GET http://localhost:3000/username:apitoken#https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found)
Edit:
My current approach:
function getJiraTicket() {
axios.get(`${userName}:${apiToken}#https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
auth: {
username: userName,
password: apiToken,
},
withCredentials: true
})
.then((res) => {
const data = res.data;
console.log(data);
setJiraTicket(data);
})
.catch(err => {
// This error means: The request was made and the server responded with a status code
if(err.res) {
console.log(err.res.data);
console.log(err.res.status);
console.log(err.res.headers);
console.log("request was made and server responded with status");
// The request was made but no response was received
} else if (err.request) {
console.log(err.request);
console.log("request was made, but no response was received");
// Something happened in setting up the request that triggered an error
} else {
console.log("Error", err.message);
console.log("request is note set up correctly");
}
console.log(err.config);
})
Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"
Endpoint that works well in Postman (Basic auth is provided in Postman):
https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid
Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly. This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication. However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:
https://auth.atlassian.com/authorize? audience=api.atlassian.com&
client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent
Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues
Axios uses a headers config for get/post so you should not include them in your URL. Here is a general example of how you should construct the URL and apply headers:
let axiosUrl = `https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
baseURL: axiosUrl,
method: 'get',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin", "*"
},
//timeout: 2000,
auth: {
username: userName,
password: apiToken,
}
})
.then((res) => {
setJiraTicket(res.data);
})
.catch(function (error) {
console.log(error);
});

how to solve 401 error in react native web?

I am trying to make an axios get request but am receiving 401 everytime am trying to fetch. However am already logged in as I have previously received my user login response
My project has been built with react native init and is running on browser using react-native-web.
The same api when I check the response on mobile and postman it is giving the correct response however on browser it is throwing 401
below is my axios code
useEffect(() => {
let url = `${ROOT}/children/${id}/vaccinations`;
axios
.get(url)
.then(function (res) {
console.log("Hello", res);
setData(res.data.content);
})
.catch(function (err) {
console.log(err);
});
}, []);
The response of 3 apis that are being called
The error that am receiving
[![enter image description here][2]][2]
could anyone please tell me where am going wrong?
any help would be appreciated.
[2]: https://i.stack.imgur.com/17Qyf.png
401 code error means you are not authorized, you would need to send your user token that you receive from the backend as a header when sending your specified request, something like that:
axios.get('https://api.github.com/user', {
headers: {
'Authorization': ${access_token}
}
})
You can read more about sending tokens in headers via this link:
https://flaviocopes.com/axios-send-authorization-header/
I hope this helps in solving your issue.

React+axios api call returning 401 error, postman is able to get access

first time posting.
I am building a simple react app to display a list from an api that has basic auth. I am able to use postman and curl to successfully access the api and display the info. However when I try and call it in my code, I get a 401 error from the browser. I've tried a few variation of the code below and think that this is the closest to working. Many thanks in advance to any that can help or point me in the right direction. Also I have cors disabled as this just a frontend.
componentDidMount() {
const tok = 'KEY:password';
axios.get('https://api/*********/assets',
{headers : { 'Authorization' : 'Basic ' + tok }})
.then(function(response) {
console.log(response.data);
console.log(response.headers['Authorization']);
}).catch(err => console.log(err));
}

Resources