Store cookie connexion with Axios - javascript

I would like to have access to the information of an api with Axios, the problem is that Axios can't get the data. I have tested with Postman and I can access the data well.
I also noticed that Posteman stores a login cookie, I tried to reproduce with Axios but I can't.
I saw that axios.defaults.withCredentials = true had to be used, but it doesn't work, maybe I'm doing it wrong.
Here is my code:
getData() {
axios.defaults.withCredentials = true;
let url = "***"
axios
.get(url)
.then(response => {
this.name = response
}).catch((error) => {
this.name = error;
})
}
Thank you in advance!

Is this a NodeJS application? You may need to install something like tough-cookie. I was shown recently that https://github.com/salesforce/tough-cookie can be used to store cookies during your axiosJS requests. This could be helpful when a cookie is assigned after the request, such as during a 302 redirect.

The postman cookie is juste postman stuff if you didn't set it yourself, so it might not be useful for your axios request
Careful tho, axios returns the data like {"headers": stuff, "data": yourdata} where Postman just displays the data that's in the "data" key
So you might want to do
getData() {
let url = "***"
axios
.get(url)
.then(response => {
this.name = response.data
}).catch((error) => {
this.name = error;
})
}
otherwise, you can export your request Postman to code so you will see what Postman sends to the API (use the 'Code' button in Postman, under the 'Save' button)

Related

How can I get the image URL from a LinkedIn post using the Post API?

I am trying to get the URL of all the media inside of an organization post but all I can get is the image URN. I don't want to do another request to get the image but rather get the Posts information and the URL on the same call.
I tried to use the Posts API as the UGC Post API is currently marked as Legacy.
let testresp = await axios.get(https://api.linkedin.com/rest/posts?q=author&author=`urn%3Ali%3Aorganization%3A${LinkedInHelpers.URNtoID(orgsRes.data.elements[0].organizationalTarget)}`&fields=id,content:(media), {
headers: {
'Authorization': `Bearer ${accessToken.data.access_token}`,
'X-Restli-Protocol-Version': '2.0.0',
'LinkedIn-Version': '202301'
}
})
I also tried to use the ~ decorator to get extra data on the Media but it returns an empty object.
Hello please try making the get request add this address instead https://api.linkedin.com/v2/ugcPosts/${postId}
Try this :
axios.get(`https://api.linkedin.com/v2/ugcPosts/${postId}`, { headers })
.then((res) => {
const imgUrl = res.data.media_url;
console.log(imgUrl);
})
.catch((e) => {
console.error(e);
});

how to send response recaptcha token to backend using axios

I am using vue-recaptcha v3 on vue2 , and when I log response data of recaptcha request it is a fullfiled promise with a token and when I test it via postman and google verify api, it gets succeed.
but I don't know how to parse this promise and send the token to the Node backend using axios, my axios section doesn't work and I Get empty object {} at the backend side. anyone can help please?
methods: {
loginFunction: function() {
this.$recaptchaLoaded();
const token = this.$recaptcha('login');
console.log(token);
axios.post('http://192.168.27.167:3000/recaptcha',
{
token: token,
})
.then(response => {
}).catch(error => {
console.log(error)
})
it solved by a friend of mine as below with adding Async Await to the code and then at console log I get pure token to using for verification.
methods: {
loginFunction: async function() {
await this.$recaptchaLoaded();
// Execute reCAPTCHA with action "login".
const gresponse = await this.$recaptcha('login');
console.log(gresponse)

Why axios somehow modifies the id of the tweets after parsing twitter search api response?

I am using axios to execute GET request to twitter search api in order to retrieve recent tweets that use a particular hashtag.
First I tested the twitter search API through postman and I see the id and id_str tweet status response property is consistently equal.
Now using axios the id value is changed and I don't know why. Below I posted my example axios request inside nodejs express controller function.
exports.postTestTwitter = async (req, res, next) => {
const requestData = {
headers: {
Authorization: 'Bearer FooToken'
}
};
const hashTag = req.params.hashTag;
const requestUrl = 'https://api.twitter.com/1.1/search/tweets.json?q=%23' + hashTag + '&result_type=mixed&until=2020-12-24';
const twitterPosts = await axios.get(requestUrl, requestData)
.then((tweets) => {
return tweets.data;
});
return res.json(twitterPosts);
};
The parsed status from the response is the following.
Can I rely axios won't change some other ids of integer values of other APIs other than Twitter? Why is this happening?
For now, I will be using id_str since this is the correct id of the tweets.
I think its because axios isn't able to handle larger integer values came across this issue once saw another answer here

Is it possible to send delete/put requests to a Azure AD secured api or get jwt Token as String using aadHttpClientFactory

I have a custom Api which I secured with Azure AD like the following tutorial:
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient
Thats working great.
now I have the following Code to make a GET request to my custom API (working):
this.context.aadHttpClientFactory
.getClient('MY_API_URL')
.then((client: AadHttpClient) => {
console.log(AadHttpClient.configurations.v1);
return client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1
);
})
.then(response => {
var res= response.json();
return res;
}).then( (res: any[]) => {
...
HERE I WOULD LIKE TO GET MY TOKEN
});
So this is working how I expect it to work.
But the aadHttpClientFactory only supports GET and POST requests
Now my Idea was to just make some PUT/DELETE requests with jQuery and use the Bearer token I got above (tested with postman and its working).
But then I realised, that I won't get the token that easy.
When I console.log(AadHttpClient.configurations.v1) I only get this:
Sure I could just change my API to use POST instead of PUT/DELETE but that would be pretty ugly
Does anyone has an Idea on how I could get the token as a String to do custom requests with it?
AadHttpClient supports the fetch(url, configuration, options) method, where options can include all of the request configuration options supported by the Fetch API.
So, to make a DELETE request, you would do something along the lines of:
client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1,
{
method: 'DELETE'
}
);
I solved it now.
Maybe my answer will help someone later.
according to philippe Signoret's answer the is the fetch() function.
I had to use it like following:
this.context.aadHttpClientFactory
.getClient(api_url)
.then((client: AadHttpClient) => {
return client
.fetch(
MY_URL,
AadHttpClient.configurations.v1,
{
method: METHOD, //put/DELETE etc.
headers: [
["Content-Type", "application/json"]
],
body: JSON.stringify({
YOUR REQUEST BODY
})
}
)
});

javascript HTTP GET using Fetch API returns 401 Unauthorized but works in Postman

I've searched for already solved similar answers but no one helped, maybe I missed some small but important detail, please give me a hint.
I'm trying to make ordinary HTTP GET authorized request using Fetch API. It successfully works in Postman, but I cannot reproduce the same success in form of js code...((
The js code: https://codepen.io/iexcept/pen/jpEQgm?editors=1011
var url = 'https://core1.dev.bravais.com/api/v3/context/update';
document.cookie = 'Bravais-dev-Context="pP9xIpeU3JXF6+KIVtz2P/8bXJUq5A5FtRSfhDpA2ZrAgUqDOZZfuKnMvLPncMuDgj2Su8trzdDAzB5kAOcAmVD5sh95KdIBRlkyioIZeds8rXn0kk6XjfkWHs/L4jNZYWho4RsW3nELC4u9pO/V4uX6LhsG/LI7Qwsgtd0NTNj4aN4/uu92bESX2F0UZv5SZmRPsdtnCB1pIXpqf0KZ5ZqRdd8+R/wuHfeb6jsy5QI=";Domain=.dev.bravais.com;Path=/;Secure';
fetch(url, {
credentials: 'include', // include the cookie needed for authorization
})
.then(response => response.json())
.then(data => {
console.log(data) // Prints result from `response.json()`
})
.catch(error => console.error(error.toString()));
"TypeError: Failed to fetch"
Even the Chrome's ~"Allow CORS" extension doesn't help. It's installed and enabled:
But! the request works fine in the Postman app (with added the same auth cookie of course), proof:

Categories