Axios not working in AWS Lambda with Google Servers - node.js

I am currently experiencing a weird issue.
I use axios in my NodeJS Lambda (AWS) to verify a Google Recaptcha Token.
However, this request to Google via axios.post() takes forever and therefore the Lambda function gets a timeout. (10s)
At first I thought it might be the VPC or the Security Group but no, I commented out the request and sent another request via axios which works.
Only the one via Google does not work. (On my local machine it works of course).
The code I use for posting to Google:
const response = await axios.post(
`https://www.google.com/recaptcha/api/siteverify?secret=${recaptchaSecret}&response=${event.token}`
);
I have already put a try / catch block around it and no errors are printed / catched.
Looking forward to your suggestions.
Thanks.

Related

How to display binary images retrieved from API in React.js?

✨ Hello everyone!✨
General Problem:
I have a web app that has about 50 images that shouldn't be able to be accessed before the user logs into the site. This should be a simple answer I suspect, there are plenty of sites that also require this basic protection. Maybe I do not know the right words to google here, but I am having a bit of trouble. Any help is appreciated.
App details:
My web app is built in typescript react, with a node.js/express/mongoDB backend. Fairly typical stuff.
What I have tried:
My best thought so far was to upload them into the public folder on the backend server hosted on heroku. Then I protected the images with authenication middlewear to any url that had "/images/" as a part of it. This works, partially. I am able to see the images when I call the api from postman with the authenication header. But I cannot figure out a way to display that image in my react web app. Here is the basic call I used.
fetch(url,
{
headers: {
Authorization:token,
},
}
);
and then the actual response is just an empty object when I try to copy it
{}
but I also get this when I console log the pure response, some kind of readable stream:
from following related question
I came up with the following: (which is normally wrapped in a asyc function)
const image = await fetch(url,{headers:{ Authorization:token}});
const theBlob = await image.blob();
console.log(URL.createObjectURL(theBlob));
which gives me the link: http://localhost:3000/b299feb8-6ee2-433d-bf05-05bce01516b3 which only displays a blank page.
Any help is very much appreciated! Thanks! 😄
After lots of work trying to understand whats going on, here is my own answer:
const image = await axios(url, { responseType: "blob", headers: {Authorization: token }});
const srcForImage = URL.createObjectURL(image.data)
Why it makes sense now
So I did not understand the innerworkings of what was going on. Please correct me, but the following is my understanding:
So the image was being sent in binary. What I had to do to fix that was to set the reponseType in axios as "blob", which then sent a blob, which I believe means its base 64 encoded instead. Then the function URL.createObjectURL does some magic, and must save it to the browser as part of the page. Then we can just use that as the image url. When you visit it yourself, you must type the 'blob:' part of the url it give you too, otherwise its blank, or stick it in <img src={srcForImage}/> and it works great. I bet it would've worked in the original fetch example in the question, I just never put the url in a tag or included 'blob:' as part of the URL.
That's correct, you send the auth token and the backend uses that to auth the user (check that he exists in the DB, that he has the correct Role and check the jwt too)
The server only responds with the images if the above is true
If your server is responding with an empty object then the problem is the backend not the frontend, console.log what you're sending to the frontend

axios network error with cors activated still returns error

the link to the code link
I am using axios and nodejs.
All routes work and give a response except one. which returns Network error.
that route is /api/ads/myads.
The route works on its own but when used with redux actions it doesn't
The network tab says that this request was blocked.
So I tried to add cors but that didn't solve the issue.
The file in question is .../actions/adActions this one is producing the error while others don't
I will be uploading the code in a minute
This turned out to be my adblocker thinking this was actual ads

HTTP POST from Google Cloud Functions Node.js?

A similar question is already asked, but the suggested answer requires request.post, but "request" is now deprecated. There is no suggested on alternative methods.
HTTP POST Google Cloud Functions NodeJS
Problem:
I've been looking for this for two days. I am simply looking for a bit of example code to send a POST request from a Google Cloud Function. I will pass a small bit of data and an auth token, but can't figure out the correct way to do it.
I will hit the API via HTTPS url and pass along the following parameters:
-d arg="1234" (a string)
-d access_token=0809809cx089009xci3 (an access token)
There are a million docs on how to trigger a cloud function from a POST, but nothing on how to actually generate the POST from within the cloud function.
Thanks in advance!
You can use libraries other than "request", for example: got, axios, or the default "HTTP" module in the standard node library. Checkout 5 Ways to Make HTTP Requests in Node.js.
Here is an implementation using "got":
const got = require('got');
const searchParams = new URLSearchParams([
['arg', '1234'],
['access_token', '0809809cx089009xci3'],
]);
got.post('https://example.com', { searchParams });

Send data to Google Cloud Function using Postman

very new to server side programming, so my apologies in advance
I created a google cloud function that calls an API (i figured that part out it works ), the cloud function is invoked via http. for my environment am using Node Js and am using axios to make api call from within my gcloud function
now am stuck on 1) how do I send the data to the gcloud function (I am assuming a POST, and am also assuming it is sent in the body?) at the moment am using Postman to call the gcloud function. I have been experimenting with variations but I get nothing but Internal Server Errors.
2) How to use the parameters I sent to the google cloud function.
am assuming something like below? but am really not sure
exports.helloWorld = async(x,y,req, res) => {
thanks in advance
Yes, you are correct, POST is one of the most used methods to send data via your calls. You need to look out into some specific topics, such as for the type of data that you will be sending and how it's going to be handled and with CORS (Cross-origin resource sharing
) as well, since it be will crossing origins and this usually causes errors.
Including that, you are almost correct on how to use the parameters. It will look more like this below - this code and other examples are available in the official documentation.
exports.helloWorld = functions.https.onRequest((req, res) => {
// ...
});
You can continue to use Postman to call the functions, but you can use a cURL as well, to do that. The cURL will be something like this:
curl -X POST "https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/FUNCTION_NAME" -H "Content-Type:application/json" --data '{"name":"Keyboard Cat"}'
I would recommend you to take a look at the official documentation Call functions via HTTP requests to get a better understanding of how it works. Besides that, this other post from the Community here, should provide you with a complete example of Cloud Functions with HTTP and Node.js.
Let me know if the information helped you!

Unable to get redirect response from Node server using res.writeHead() and .end()

I'm writing a server in Node.js. I've been using the send-data/json package to send responses, with much success. For example, at the end of my API call I use this code:
sendJson(res, res, {some: content})
This works great. However, I have a need to implement a URL redirect in one of my API endpoints. The code I am seeing everywhere to do this looks like this:
res.writeHead(302, {Location: 'http://myUrl.com'})
res.end()
However, this change causes my server to stop sending responses on this endpoint.
What am I missing?
Note: this is vanilla Node without Express.
Update: to clarify, based on contributions in the comments, this is the result of a GET request, so I expect that redirects should be enabled by default. I am still curious why no response is coming back from the server at all, regardless of whether it is an erroneous redirect attempt or a successful one.

Resources