Send data to Google Cloud Function using Postman - node.js

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!

Related

Axios not working in AWS Lambda with Google Servers

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.

Creating a Node.js REST API using Firebase Cloud Functions, without Express?

I am working to create a serverless REST API via Firebase Cloud Functions, which seems to work well but the examples and documentation all seem to use a monolithic solution, since they use the Express framework and essentially map the root http request to the Express app, then let it handle the routing. I understand that this is because the Firebase Hosting platform does not have the ability to handle http verbs.
My expectation was that a serverless / FaaS approach would have a function for each endpoint, making for easy updates in future since there's no need to update the whole app, just that single service - i.e. a more functional approach.
What am I missing here? Why is the approach to use a single function to contain an express app? Doesn't this defeat the purpose of a serverless / Cloud Functions approach? And is there any other way of doing this?
The documentation shows how to create an endpoint without the help of an Express app, router, or middleware:
exports.date = functions.https.onRequest((req, res) => {
// ...
});
All you have to do is arrange to send a response with res.send(...) or similar.

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 });

HTTP POST Google Cloud Functions NodeJS

How do I write a Google Cloud Function that will receive a HTTP request and then send a HTTP POST request to a different endpoint?
For example,
I can send the HTTP trigger to my cloud function (https://us-central1-plugin-check-xxxx.cloudfunctions.net/test). I am using exports.test = function helloWorld(req, res){} to process the data received.
And then I want to send the processed data with a HTTP POST request to a different endpoint.
By far I have tried sending HTTP POST with node-webhooks, request & restler modules but none of them seem to work. Is it because these modules are used in conjunction with exports.test ?
My question is related to this question but the answers didn't help me.
The data being sent to endpoint is in json & Content-type: application/json.
var request = require('request'); //also tried for node-webhook, restler modules
exports.test = function(req, res) {
//processing of received json data from source A.
}
function sendToEndpoint(processed_data) {
let abc = processed_data; //send processed data to source B
request.post({
uri: 'https://example.com',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(abc)
});
}
As #RenaudTarnec mentioned in the comments the problem was that my billing account was not configured.
Google doesn't allow outbound requests to external servers without valid billing info so as to prevent any malicious activity.
After configuring a billing account I was able to make outbound requests and all the node-modules mentioned in the question worked.
Within a Cloud Function that is written in Node.js, you can use any package that is accessible via NPM. Using Google Search to find such packages shows:
5 Ways to Make HTTP Requests in Node.js
Calling a REST API from a NodeJS Script
REST Client for Node.js
4 + 1 ways for making HTTP requests with Node.js: async/await edition
Unirest for Node.js
... others
Which one you choose is usually a matter of taste. My personal choice is to use the one which does the job and is most popular. I equate popularity with liklihood of on-going support and updates.
Use Websockets
SOCKET.IO is the best choice. https://socket.io/
However it is impossible to use this in cloud functions. Because it is distributed in different machines. So keeping track is impossibe.

How to send a http response using koajs

I'm trying to validate a webhook via facebook. So facebook hits my url my-url/facebook/receive within my route in nodejs i'd do res.send(req.query['hub.challenge']); to send an http response.
I'm using KoaJS. From what i understand, Koajs merges the request and response object into ctx but when reading through the docs I can't find anything along the lines of ctx.send or similar to send a http response.
Can anyone give me some direction or links.
Thanks.
To send the body of a response, you can simply do ctx.response.body = 'Hello'. There are many aliases attached to ctx, so you don't necessarily have to reference the response or request yourself. Doing ctx.body = 'Hello' would be the same as the code above.
If you wanted to set headers, you would use the ctx.set() method. For example: ctx.set('Content-Type', 'text/plain').
To access the query parameters, you would use ctx.request.query['some-key'] (or simply the alias ctx.query['some-key']).
All of the different request/response methods are documented pretty well at the Koa website along with a list of aliases attached to ctx. I highly recommend you give it a read.

Resources