HTTP POST Google Cloud Functions NodeJS - node.js

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.

Related

GET request recieved in php but not node.js w/ Express

I'm trying to integrate KiwiWall, a rewarded ads/offerwall provider, with my website. The end goal is to credit virtual coins to the user when an offer is completed.
The code that I currently have is as follows. I'm simply trying to make sure a request is being received from KiwiWall, which it is not. It's worth noting that the following DOES log the intended information to the console when a request is sent from my browser or a request testing website like ReqBin:
app.use('/offers/kiwiwall/api', cors(), async (req, res) => {
console.log(req.method)
})
However, no output can be seen when using the postback testing functionality of KiwiWall.
In order to make sure the issue isn't on KiwiWall's end, I hosted the example php code from the KiwiWall docs on the same webserver, and was able to successfully receive and process the request using it. Why is this not working with node.js/Express?

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!

Difference between express.js and axios.js in Node

We use axios for http requests such as get, post, etc.
We use express for the same purpose also.
However according to what I read, they are for different purposes.
Please explain how.
PS: If you explain it by giving an example, it would be great!
You can think of express.js as a warehouse:
app.get('/item/:name', async function (req, res) {
res.send(await findItemByName(req.params.name));
});
If you want to get an item, for example a pencil, from this warehouse, you can use axios.js.
axios.get('/item/pencil')
Axios is used to send a web request whereas express is used to listen and serve these web requests.
In simple words, express is used to respond to the web requests sent by axios.
If you know about the fetch() method in javascript, axios is just an alternative to fetch().
I would say that express is used to create HTTP servers. So the server runs somewhere and responds to a request.
Axios is an HTTP client. It creates requests!
In very simple words axios is just passing the web request to the server-side (express). They basically work together (axios -> express -> DB)

What does http and https module do in Node?

Can someone help me in understanding what does http and https module do in Express?
I was going through the following docs on w3schools
From definition it says
Node.js has a built-in module called HTTP, which allows Node.js to
transfer data over the Hyper Text Transfer Protocol (HTTP).
With following example
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
This is the example to live demo
First, I am unable to comprehend their example like Where are they making (route) request so that they are receiving response?
Second by the definition, to make a request, using libraries like axios can be alternative?
third, when we make an api request, isn't the data transferred over http/https?
app.post("/", (req, res) => {
In short, Can someone please explain me in more human words the use of http package in express?
Update: I might be confusing this with express, I am used to using express and here we aren't using express
1- They aren't defining any route. That piece of code only creates a server running on port 8080 that when it's created or accessed on the home route (/) returns "Hello World". If you want to define routes you should take a closer look to a module called express that it's used by most of node users due to its simplicity and documentation (https://expressjs.com/en/starter/hello-world.html) In that link you have an example for creating the server and a basic route
2- Yes it can and should be because they are way better than the default from nodeJs. Take a look at axios or superagent, superagent it's better if you want to use formdata to send images or attachments.
3- By default, all servers created using http or express are http servers (don't have a certificate to encrypt the data so they aren't secure). If you want a https server, you can buy certificates or use https://letsencrypt.org/ this module that generates free SSL certificates with 1 month validation.
http module has multiple functions, it can be used to create a server, to make http requests and so on. It's up to you to decide which submodule from the package you want to use. Express is built over the http module making everything easier.
If you need more explanation, tell me and I will try to explain a little better.

Resources