Axios Get not resolving - node.js

I'm trying to make a simple GET request with axios that follows the redirect until network idle, but I can't get the promise to resolve. It seems to work for most urls, but not the below url, specifically - not sure if there's an issue with my code or something peculiar to this one redirect (others of similar format work fine, ie with different mid=XXXX parameters.
A GET request (with no headers or authorization) redirects fine in Postman, but axios won't return anything.
async function axiosGet() {
try {
const response = await axios.get("http://www.awin1.com/awclick.php?mid=4802");
console.log(response);
return response;
} catch (err) {
console.log(err);
}
}
Running this I only get back back my bash prompt with nothing logged. Assigning my axiosGet() function to a variable, and then logging that variable only yields Promise { <pending> }. Just looking to get a resolved promise object, good to go from there.

Related

Axios in node.js check url before executing code

I dont find anything that works for me so I ask here:
I am trying to get some data from a website with axios. It works great, but if I input the wrong URL I get an error. I want to check if the URL with its complete path to the page I desire exists.
I tried npm package url-exists but it just said the path didn't exist eventho it did.
Is there a simple way to check if a path like for example "https://github.com/enterprise" exists or if it doesn't?
You have to make a request anyway to check if the url exists. So you can handle it when you got 404 status code in catch error block of axios function.
The only way is making the request, you can handle this scenario using a try/catch block
const getSomething = async () => {
try {
const something = await axios.get("www.website.fake")
} catch (err) {
throw new Error(err)
}
}

How to modify a response in Electron

Let's say that I'm using a GET request on https://example.com and the response is this:
This is a response message.
How would I modify it in a way so that in my code, so that it can change the response to say something like this:
This is a MODIFIED response message.
For example, if my Electron app were to navigate to https://example.com, the screen would show me the modified content instead of the original content.
Essentially, I am trying to literally modify the request.
I have based my code off of this question but it only shows a proof of concept with a pre-typed Buffer, as in my situation I'd like modify the response instead of outright replacing it. So, my code looks like this:
protocol.interceptBufferProtocol("http", (req, CALLBACK) => {
if(req.url.includes("special url here")) {
var request = net.request({
method: req.method,
headers: req.headers,
url: req.url
});
request.on("response", (rp) => {
var d = [];
rp.on("data", c => d.push(c));
rp.on("end", () => {
var e = Buffer.concat(d);
console.log(e.toString());
// do SOMETHING with 'e', the response, then callback it.
CALLBACK(e);
});
});
request.end();
} else {
// Is supposedly going to carry out the request without interception
protocol.uninterceptProtocol("http");
}
}
This is supposed to manually request the URL, grab the response and return it. Without the protocol event, it works and gives me a response, but after some debugging, this piece of code consistently calls the same URL over and over with no response.
There is also the WebRequest API, but there is no way of modifying the response body, you can only modify the request headers & related content.
I haven't looked fully into Chromium-based solutions, but after looking at this, I'm not sure if it is possible to modify the response so it appears on my app's end in the first place. Additionally, I'm not familiar with the Chromium/Puppeteer messages that get sent all over the place.
Is there an elegant way to have Electron to get a URL response/request, call the URL using the headers/body/etc., then save & modify the response to appear different in Electron?

TypeScript: how to handle async functions inside setTimeout()?

I have the following timed function to periodically refetch credentials from an external API in your usual movie fetching IMDB clone app:
// This variable I pass later to Apollo Server, below all this code.
let tokenToBeUsedLater: string;
// Fetch credentials and schedule a refetch before they expire
const fetchAndRefreshToken = async () => {
try {
// fetchCredentials() sends an http request to the external API:
const { access_token, expires_in} = await fetchCredentials() as Credentials;
tokenToBeUsedLater = access_token;
// The returned token expires, so the timeout below is meant to recursively
// loop this function to refetch fresh credentials shortly before expiry.
// This timeout should not stop the app's execution, so can't await it.
// Have also tried the following with just setTimeout() and
// no `return new Promise()`but it throws a 2nd identical error.
return new Promise(resolve => setTimeout(() => {
resolve(fetchAndRefreshToken());
}, expires_in - 60000));
} catch (err) { throw new Error(err); }
};
fetchAndRefreshToken(); // <-- TypeScript error here
I have tried rewriting it in a thousand ways, but no matter what I do I get a Promises must be handled appropriately or explicitly marked as ignored with the 'void' operator error.
I can get rid the error by by:
Using .then().catch() when calling refreshToken(). Not ideal since I don't want to mix it with async and try/catch.
Putting a void operator ahead of refreshToken(). Feels like cheating.
Putting await ahead of refreshToken(). Essentially breaks my app (pauses execution of the app while waiting for the token to expire, so users in the frontend can't search for movies).
Any idea about how to solve this?
Also, any suggested resources/topics to study about this? Because I had a similar issue yesterday and I still can't figure this one out despite having already solved the other one. Cheers =)

Why is res undefined in some cases?

I'm working on a ReactJS project and I'm using Axios to connect to my NodeJS backend using express and a MongoDB Database.
I have a button in my render function that when clicked calls the following function:
getInfo() {
Axios.get('http://localhost:9000/getMyData')
.then(res => console.log(res));
}
This works fine, it connects, queries my database and I can see the results in my console.
BUT
If I try to set the state with this result, it is undefined.
For example:
getInfo() {
Axios.get('http://localhost:9000/getMyData')
.then(res => this.setState({data: res})); // or res.data based on the way I want to save it
}
I get a 304 response instead of a 200 response, and React says that res is undefined.
I do not understand what is going on here, why can I console log the response, but I can't store it.
Can someone please explain to me what I am doing wrong, and how I can store the data?
Thank you.

PUT is blocking GET?

I am trying to intercept a PUT request using nock, but something is going really strange...
My code has 2 calls, a GET request
http://internal-jira.com/rest/api/2/issue/CCC-2142
and a PUT request with payload
http://internal-jira.com/rest/api/2/issue/CCC-2142
{ fields: { reporter: { name: '8778469' } } }
The process is that it does the GET then uses info from there to do the PUT.
So I have also created 2 mock calls, one for the GET
nock('http://internal-jira.com.com', {allowUnmocked: true}).persist()
.get(/\/rest\/api\/2\/issue\/.*/)
.reply(400, (uri) => {
console.log(`!!!! Mocked GET: ${uri} !!!`);
})
and one for the PUT
.put(/\/rest\/api\/2\/issue\/.*/)
.reply(400, (uri) => {
console.log(`!!!! Mocked PUT: ${uri} !!!`);
})
If the GET code is active and I run my code then I can see that the code is being caught as I get the console.log()
!!!! Mocked GET: /rest/api/2/issue/CCC-2144 !!!
But if I comment out the GET and enable the PUT when I run my code, it fails and errors at the GET without it being mocked.
Its as if the PUT mock, is somehow intercepting the GET request (I guess as the URL is the same) but not actually doing anything with it, but also not letting the GET request through?
What am I doing wrong?

Resources