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 });
Related
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.
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!
i am creating a node application which will use a another node backend, like a CLI program, which Node.js library or framework will i use for this situation? the axios not is working in my tests.
thanks for reading.
If you want to do http requests from within node.js there are several options: https://www.npmjs.com/package/node-fetch, axios is also available. Could you please share some errors you get?
I always use node-fetch because I am most familiar with the fetch API, previously I used this package: https://www.npmjs.com/package/xmlhttprequest
As seen in your answer you are using /users as url, please use the full url. Also catch any unexpected errors.
So axios.get('http://domain/users')
I SOLVED THE PROBLEM!
the problem was in the axios connection, now its:
async function execQuery(apps){
data = ({
name: "ederson",
apps: "neofetch"
})
const response = await axios.put('http://localhost:3333/users', data
).then(console.log(apps))
}
Thanks for help me, Laurent Dhont and Ahmed Hammad!
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.
I built a custom webhook as a fulfillment endpoint for a Dialogflow intent. It works fine when I respond with raw JSON, ie: {'fullfillmentText':'hi'},
but does not seem to work using the "actions-on-google" library.
The code from their website implies this should work:
app.intent('myintent', (conv) => {
conv.close('See you later!');
});
But it does not. Google Home just says my app isn't responding. It might be that as it stands my function (using Fn Project) has to return JSON and if I return JSON as a response that it isn't expecting it fails. Maybe someone can shed some light?
Edit 1:
I'm using a custom webhook using the Fn Project open source functions as a service. Demonstrating how to use the project is my purpose here so I don't want to use inline editor or Google Cloud Functions or firebase or any other default option.
Here's the rest of the code
const fdk = require('#fnproject/fdk');
const request = require('request');
const dialogflow = require('actions-on-google');
const app = dialogflow({
debug: true,
});
fdk.handle(function (input) {
app.intent('myintent', (conv) => {
conv.ask('I could not understand. Can you say that again?');
});
return {'fulfillmentText': 'response from webhook'}
});
Although you are creating the app object, which does the Intent handler processing and such, and registering a handler with it via app.intent(), you're not doing anything to "export" it so app's methods are called when the webhook is triggered. When called, it gets the body of the request and will format the JSON for the response.
If, for example, you were using Firebase functions, you would connect app to be handled through the functions with something like
exports.fulfillment = functions.https.onRequest(app);
But you're not. You're using a different framework.
The library comes with a number of frameworks that are supported out of the box, but the Fn Project isn't one of them. In theory, you can create your own Framework object which will do this for you (the "Frameworks" section of this article discusses it briefly, but doesn't go into details about how to do so).
As you surmise, it may be easiest for you to just read the JSON request and generate the JSON response yourself without using the actions-on-google library. Or you can look into a library such as multivocal to see if it would be easier to leverage its multi-framework support.