Firebase Function Error - Error: could not handle the request - function

const functions = require('firebase-functions');
const request = require('request');
exports.sendtest = functions.https.onRequest((requests, responses) => {
var id = 'test';
var num = 'test';
url='https://myurl.com/test.php?id='+id+'&num='+num;
request({
url: url,
method: 'get',
}, function (error, response, body) {
if (error) throw error;
response.redirect(body);
});
});
When I deploy and run the code I am getting error like
Error: could not handle the request
I don't know why I am getting such error.

This is because plan is free one. So it doesn't allow to connect outside google server.

Related

Send JSON Data to Google Cloud Functions using Express.js Routing

Can anyone please help me to understand, why am I getting errors while calling the google cloud function, whereas I'm not getting an error if I'm calling the same function locally.
PFB the code of the function, that I'm calling from
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded());
var n1 = null;
var n2 = null;
app.get('/sum', (req, res) => {
n1 = Number(req.query.n1 || req.body.n1);
n2 = Number(req.query.n2 || req.body.n2);
res.json({
"n1": n1,
"n2": n2,
"result": n1 + n2
})
});
app.listen(3000);
exports.calculator = app;
Javascript code of the call made to google cloud function:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"n1":1,"n2":2});
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://us-central1-testing-297304.cloudfunctions.net/calculator/sum", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
All the requests either local or to cloud function is made through Postman
Error that is given by gcp:
Calling your function returns "Cannot GET /sum" error because requests with GET/HEAD method cannot have body. What you should to is to change your request to POST (on your code and also your Postman request).
app.post('/sum', (req, res)
and
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
I did that on my test function and I was able to get a 200 OK with an output using Postman.

HTTP Get request from api and load results to Mysql

I'm making a http GET request and will like to load results of API to Mysql db. code is below. My Db connection is working and i'm not getting any errors. I'm just not getting any results loaded into the db. what am I missing?
var request = require('request');
var mysql = require ('mysql');
var express = require ('express')
let config = require ('./config.js')
let connection = mysql.createConnection(config);
var app = express ();
var bodyParser = require('body-parser')
require('dotenv').config()
// start api operation from db
var options = {
'method': 'GET',
'url': 'https://......,
'headers': {
'Cookie': ''
};
request(options, function(error, response) {
if (error) throw new Error(error);
console.log('getting the goods');
});
// end api operation
//start body-parser configuration
app.use(bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//end body-parser configuration
//create app server
var server = app.listen(3000, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("i'm getting your data at http://%s:%s", host, port)
});
// get data from customer api...
var sql = `INSERT INTO dbname
(id, email, created_at, updated_at, first_name, last_name)
VALUES ( '"+rec.body.id+"', '"+email+"', '"+created_at+"', '"+updated_at+"', '"+last_name+"', '"+first_name+"')`;
var dbname = ['"id+"', '"+email+"', '"+created_at+"', '"+updated_at+"', '"+last_name+"', '"+first_name+"']
console.log ("working")
connection.query(sql, [dbname], (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get insrerted rows
console.log('Row inserted:' + results.affectedRows);
});
// close the database connection
connection.end();
console.log("disconnected")

FeathersJS Error Handler Unexpected Token < Issue

I am working on an Express App with MongoDB and trying to utilize FeathersJS for all my services. Here I'm running a test try to get an error message from the server to the client, but I have an issue with the response from the error handler. My req headers have the correct application/json stuff, so I assumed the Error Handler should send valid json back.
I know I'm not using the next callback in my function, but when I try to do that it gives the same error, so I'm thinking it has to do with the Error Handler. Any direction here would be greatly appreciated!
The first error log is on the server, which is correct.
Bucket Services
error >>>>> Bucket validation failed
Possibly Unhandled Rejection: Bucket validation failed, Promise { <rejected> 'Bucket validation failed' }
>>>>>> Error: Unexpected token < in JSON at position 0
at convert (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/node_modules/feathers-errors/lib/index.js:365:79)
at toError (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/lib/client/base.js:24:37)
at process._tickCallback (internal/process/next_tick.js:103:7)
my create function within the BucketService class:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save((error) => {
console.log('error >>>>>', error.message);
if (error) { return Promise.reject(error.message); }
return Promise.resolve(new_bucket);
});
}
my router file:
const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const router = feathers();
const LoginService = require('../services/login_service');
const UserService = require('../services/user_service');
const BucketService = require('../services/bucket_service');
// Enable REST services
router.configure(rest());
router.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
router.use('/login', new LoginService());
router.use('/user', new UserService());
router.use('/bucket', new BucketService());
// Set up error handling
router.use(errorHandler());
module.exports = router;
I figured it out, the key was to correctly pass through a callback (next) function as the third parameter to handle errors. FeathersJS handles the Promise Rejections for you on errors. Then in my test I needed to convert the Feathers-Error to JSON before I could get the message.
I changed my test to:
it('can validate an incorrect bucket', (done) => {
const invalid_bucket = {
name: 'Invalid Bucket',
};
bucket_service.create(invalid_bucket, {}, (error) => {
error = error.toJSON();
assert(error.message.length > 0);
done();
});
});
and my create function to:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save()
.then(created_bucket => Promise.resolve(created_bucket))
.catch(next);
}

nodeJS - make HTTPS request, sending JSON data

I would like to send an HTTPS POST from one nodeJS server to another. I have some JSON data I would like to send with this request (populated by a html form).
How can I do this? I am aware of https.request() but there does not seem to be an option to include JSON as a part of the query. From my research it seems possible with an HTTP request, but not an HTTPS request. How can I solve this?
const pug = require('pug');
var cloudinary = require('cloudinary');
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var request = require('request');
var bodyParser = require('body-parser');
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'GET'
};
var app = express();
var parser = bodyParser.raw();
app.use(parser);
app.set('view engine', 'pug');
app.get('/', upload.single('avatar'), function(req, res) {
return res.render('index.pug');
});
app.get('/makeRequest*', function(req, res) {
query = req['query'];
/*
Here, I would like to send the contents of the query variable as JSON to the server specified in options.
*/
});
You can send JSON data through a POST http request with the native https node module, as stated in the documentation
All options from http.request() are valid.
So, taking the http.request() example you can do the following:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
You should edit postData to your desired JSON object
I believe the below is what you want. Using the request library. See comments in the code for my recommendations.
...
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'POST',
json: true
};
...
//making a post request and sending up your query is better then putting it in the query string
app.post('/makeRequest', function(req, res) {
var query = req.body['query'];
//NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request.
//(you may need to make changes on your other servers)
options.body = { payload: query };
request(options, function(err, response, body) {
if (err) {
//Handle error
return;
}
if (response.statusCode == 200) {
console.log('contents received');
}
});
});
as matt mentioned you need to use request
to send JSON object not JSON.Stringify so that at the server you can receive it using:
app.post('/makeRequest', function(req, res) {
console.log (req.body.param1);
}
Use the following code:
var request = require("request");
request({
'url':"http://www.url.com",
method: "POST",
json: true,
body: {'param1':'any value'}
}, function (error, resp, body) {
console.log ("check response.");
});

How to access the body after a get request() in nodeJs

I have tried to use JSON.parse and request.on modules but none of the examples I have seen has helped me much. Can you send me an example of accessing "body" to create an array (parsing to JSON)? I'm a newbie in nodeJs.
Thank you in advance!
var request = require("request");
var options = { method: 'GET',
url: 'URL with credentials and filter',
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});