I am trying to receive the raw response data, not the response headers or body. As an example, an image here shows the tab where this data is found:
Now, I am trying to receive this data when making an HTTP Request using `Axios`. Is this even possible?
I have tried searching online for about 2 hours, as this was a huge problem I was facing. I tried other sites, including stack overflow, to get the correct answer. If possible, could you please answer my question if you know? Thanks in advance.
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r)
})
}
I'm pretty sure you must access the data property in the response object r. Also - since you are using the reddit API - make sure you are providing api_type in the request url (api_type=json for instance):
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?api_type=json&user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r.data)
return r.data;
})
}
For anyone reading this: Just to clarify, the api_type parameter in the request url is specific to the reddit API and most likely won't work any other API.
Related
As a learner, I am trying to call the rest api. For example, you can see and copy the url from api provider as they listed on that link page.
https://docs.api.jikan.moe/#tag/top/operation/getTopAnime
function App() {
const [topAnime, SetTopAnime] = useState([]);
useEffect(() => {
fetch(`https://api.jikan.moe/v4/top/anime`)
.then((response) => response.json())
.then((data) => {
console.log(data);
SetTopAnime(data);
})
.catch((err) => {
console.log(err.message);
});
}, []);
But the question is; this does not let me to call a specific data I want to call.
To do that, I need to add some query parameters as api page written for developer.
Now, I see several examples that someone set it as follows:
const getData = () => {
axios
**.get(`${apiTop}?sfw=true&limit=20`)**
.then((res) => {
return setData(res.data.data);
})
.catch((error) => {
console.log(error);
});
};
that .get method and following code makes sense. But how that developer who coded that line knew '?sfw=true&' such thing?
If I don't understand this; what topic could be the one I should review then? I believe I understand what promises and fetch are, but not sure focusing on 'query parameter' is the right thing to solve my problem.
tl;dr
To call a specific data from getTopAnime, how should I set query parameters? (with my understanding, https://api.jikan.moe/v4/top/anime/type/movie
or
https://api.jikan.moe/v4/top/anime?=query/type/movie
is the limit to expand the thoughts.
Thanks...
From the documentation of the API -- https://docs.api.jikan.moe/
There must be API documentation where you can read about these URI structures.
Though a real REST service sends you hyperlinks with URIs or URI templates which you follow, so you need to know what type of hyperlink watch for and the service gives you the URI structure. This is called HATEOAS constraint.
I started writing a program that will automate user actions, by now it's meant to be an easier menu to make faster actions by just sending requests to the official website by clicks on my own page. (something like web-bot but not exactly).
My problem is when i send login request in response i get back user_id, server, session_id etc. And I need to save that session_id to make the other actions.
How can i save this to variable.
All in JavaScript.
I was looking in the internet since yesterday for an answer and i still can't find (or understand) how to get this
I tried
function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })
//There's the problem to solve
.then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id);
// I even tried the substring but 1. It won't work as I want because There are sometimes //more and less letters. 2. I get and error "Cannot read properties of undefined (reading //'substr')"
`session = obj;
session_id = session.substring(291,30)
console.log(session_id)`
It looks like you're using the text() method on the Response object returned from fetch(), which will give you a string representation of the response.
You probably want to be using the json() method instead, and from that you can get your session_id.
This guide has some more useful information that may help you: https://javascript.info/fetch
Ok it works now with
`async function login(){ let session = await fetch('url', {
//code
}
let result = await session.json();
console.log(result);
session_id = result.data.user.session_id;
user_id = result.data.user.id;`
I am new to node.js and APIs so I am hoping someone can help! I am trying to use node-fetch to get JSON data from the fantasy premier league API. I have successfully done this in the client, but from my node.js server file I keep getting the error:
UnhandledPromiseRejectionWarning: FetchError: invalid json response
body at https://fantasy.premierleague.com/api/entry/3/ reason:
Unexpected end of JSON input
The response itself has a status of 200, but the size is 0 so it is not returning any data. I know it should work, as the JSON is plainly visible when you visit the url and I have got fetch to work in the client-side code.
Here is the code I am using:
const fetch = require('node-fetch');
async function fetchEntry() {
const api_url = 'https://fantasy.premierleague.com/api/entry/3/';
const fetchEntry_response = await fetch(api_url);
const json = await fetchEntry_response.json();
console.log("json: " + JSON.stringify(json));
};
fetchEntry();
Note: On the client-side code I got a CORS error so needed to use a proxy (https://thingproxy.freeboard.io/fetch/https://fantasy.premierleague.com/api/entry/3/) to get it to work. I'm not sure if this is relevant?
Any help would be greatly appreciated!
Joe
Don't ask me why but adding a 'User-Agent' header seems to fix it:
const response = await fetch(URL, {
headers: {
'User-Agent': 'ANYTHING_WILL_WORK_HERE'
}
});
I think the api you're using is the problem. I tried to make it work, but got the same error. Also tried to use axios but it's the same thing.
I tried to fetch data with Postman and it worked perfectly, so.. my guess is that the api you're trying to use does not support all origin, since the API I tried to use works perfectly with your code.
const api_url = "https://randomuser.me/api";
I was facing the same problem when running the test cases. In my test case, there was the API call and I have used the useEffect react hook for updating the state.
useEffect(() => {
getDetailsFromAPI("param")
}, []);
So, While running the test case, I was getting the same error
FetchError: invalid json response body at reason: Unexpected end of JSON input
at ../../node_modules/node-fetch/lib/index.js:272:32
For solving this error I have mock the promise in the test case, which resolved my issue.
import fetch from 'node-fetch';
const mockJsonPromise = Promise.resolve(mydata); // 2
const mockFetchPromise = Promise.resolve({ // 3
json: () => mockJsonPromise,
ok: () => true
});
fetch.mockImplementation(() => mockFetchPromise);
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
A friend has an API with a GET.
I would like to know if I can send data to a lambda with a get, as if I were using a simple POST.
I have this
await axios.post(
' ENDPOINT_API',
{
resultat_net_N1:`${resultat_net_N1_form}, ${resultat_net_N1}, ${resultat_net_N1_form_1}, ${resultat_net_N1_1}`,
resultat_net_N: `${resultat_net_N_form}, ${resultat_net_N}, ${resultat_net_N_form_1}, ${resultat_net_N_1}`,
},
);
I’d like a GET that behaves like this piece of code. I don't know if it's possible. Thanks in advance.
There are workarounds, but they aren't suggested, POST SHOULD BE TO POST, and GET SHOULD BE TO GET
const res = await axios.get("/ENDPOINT_API",
{ data: {
resultat_net_N1: resultat_net_N1 }
}
)
I suggest sending them as params
const res = await axios.get("/ENDPOINT_API",
{ params: {
resultat_net_N1: resultat_net_N1 }
}
)
It all depends on the use case you are sending the data. The Get method is exposing the data as query parameters and as the name suggest it is used for getting data from the API. POST method is not exposing the data like get and is used for sending data to the API in its request body. If you try to send sensitive data it is really not recommended to use get. You can find basic difference between the http methods and their usage here