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.
Related
I try to get my data from mongoDB then use res to send all content to client side but I keep getting undefined, can anyone help me? Thank yall!!!
//// server.js
app.get('/user/show', userController.userList);
//// controller
const usersList = async (req, res) => {
const users = await User.find({});
const usersStr = JSON.stringify(users);
// tried console.log(userStr), can get correct output
res.json({'users': usersStr});
}
//// HTML Script
async function test() {
const result = fetch('/user/show',{
method: 'GET',
headers: {
'Contect-Type': 'application/json',
}
}).then((response) => response.json());;
console.log(result.messages.);
}
test();
If the data of the client come undefined myabe you dont have body-parser install.
body-parser
npm i body-parser
your index.js
const bodyParser = require('body-parser')
// app by app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true })
I have the following function working from an Angular component (in an Electron application) using HttpClient:
var auth = "Bearer" + "abdedede";
let header = new HttpHeaders({ "Content-Type": 'application/json', "Authorization": auth});
const requestOptions = {headers: header};
const url = 'https://reqres.in/api/users?page=1';
this.http.get<any>(url, requestOptions).toPromise()
.then(response=> {
//...
alert(JSON.stringify(response));
});
}
Now, here is a call from the electron side which calls the same endpoint but without the Authorization and Content-Type in the header:
let buffers:any = [];
const { net } = require('electron')
const request = net.request({
method: 'GET',
url: 'https://reqres.in/api/users?page=1'})
request.on('response', (response) => {
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
buffers.push(chunk);
})
response.on('end', () => {
let responseBodyBuffer = Buffer.concat(buffers);
let responseBodyJSON = responseBodyBuffer.toString();
responseBodyJSON = responseBodyJSON;
})
})
request.end()
(This latter function is thanks to a poster replying here: In an Electron Application I am successfully making an HTTP GET request from an Angular component. How can I do the same thing from the Electron side?)
My question is, could anybody please advise\show me how to add in the Authorization and Content-Type Header info to this call so that it replicates what the Angular version does - i.e. by passing the requestOptions data in the GET call?
Thanks.
I have found it. I needed to add:
request.setHeader("content-type", "application/json"); request.setHeader("Authorization", auth);
before I call:
request.on('response', (response) => {
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.
I need some help with my routing in Express and making a post call, and retrieving the data within the postrequest.
I've tried retrieving the data by loging req.body but that returns {}, I tried adding the bodyParser to my App.js which gets me the following error when I make a post call:
POST http://localhost:3000/enquete/test/ 400 (Bad Request)
SyntaxError: Unexpected token # in JSON at position 0
This is my code:
App.js
const express = require('express')
const app = express()
var MongoClient = require('mongodb').MongoClient
, co = require('co')
, assert = require('assert')
, bodyParser = require('body-parser');
var indexRouter = require('./routes/index.js');
var enqueteRouter = require('./routes/enquete.js');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'pug');
app.use('/', indexRouter);
app.use('/enquete', enqueteRouter);
app.use(express.static(__dirname + '/routes'));
app.use(express.static(__dirname + '/public'));
app.listen(3000, () => console.log('Example app listening on port 3000!'))
routes/enquete.js
const express = require('express')
var router = express.Router()
router.post('/test/', function(req,res,next){
console.log('request:',req.body);
res.send('hello');
})
module.exports = router;
Ajax post call
function save(array){
$.ajax({
type: 'POST',
data: { name: "Test", location: "TestUSA" },
contentType: 'application/json',
url: 'http://localhost:3000/enquete/test/',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
},
error: function(error) {
console.log('error:', error)
}
});
}
Can you use Postman to test the route? Make sure to select x-www-form-urlencoded as the body format since you're using bodyparser.urlencoded({ extended: true })
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.");
});