How to Send a payload to a firebase OnRequest Function - node.js

I have a firebase post function that I am trying to send some data to but the problem I am having is that I the body comes empty. I am using express for the function.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const express = require("express");
const request = require("request");
const moment = require("moment");
const cors = require("cors");
// const bodyParser = require("body-parser");
admin.initializeApp();
const app = express();
app.use(cors());
app.use(express.json({limit: "10kb"}));
// Mpesa Express
app.post("/express", _accessToken, (req, res) => {
console.log(JSON.stringify("FELOOOOOO", req.body));
console.log(JSON.stringify("felix"));
res.status(200).json(req.body);
});
exports.main = functions.https.onRequest(app);
The functions run but when I log the req.body it comes empty. I have used postman to send the post request but still, the req.body comes empty despite passing in some data. Kindly help solve the error. below is a screenshot of the postman request

You seem to be sending the data correctly but are incorrectly using JSON.stringify(). The object is the first argument, not the second. Make it JSON.stringify(req.body) - that should work.
You can read up more about the function over at MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Related

Why ECONNRESET error is coming in POSTMAN while making a NODEJS request

I have written a simple request response code in NODEJS but there is no response in return of the request is there .
The code for my app.js(Server file) is
const express = require('express');
const cors = require('cors')
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors);
app.use("/api",paymentroute);
app.listen(3100,()=>{
console.log(`listening to port 3100`);
})
The code for my req and res is
const express = require('express');
const router = express.Router();
// const { checkout } = require('../controllers/paymentController');
router.post("/checkout",(req,res) => {
console.log("this function is called ")
return res.json({success:"true"})
});
module.exports = router;
Even the console.log inside the res function is not working.
Just change app.use(cors); to app.use(cors());
const express = require('express');
const cors = require('cors');
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors());
app.use('/api', paymentroute);
app.listen(3100, () => {
console.log(`listening to port 3100`);
});
I think it is a connection-related issue often related to a networking issue caused by a Virtual Private Network (VPN) that in some cases is required by some API services or, in other cases, prevents you to reach an API service.
The issue seems to be a combo of having the no-cache header enabled and a request URL length over 64 characters. If the issue persists after doing this solution then try to upgrade to the latest version of Postman.

Node.js - how to use a raw request body using Express

so I was making a RESTful API and I wanted to be able to receive raw json data (so I can use my api for mobile too), then from there save the data into my database (mongoDB).
But you see, there is this problem which I can't seem to fix and its that I'm not able to use the raw data as a json.
The code is simple
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(parse.JSON(req.body));
//to convert it to json but this doesn't seem to work
})
PS. I'm using postman to send the request as raw format
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(JSON.parse(req.body));
})
inside the res.send you have to use JSON.parse() instead of parse.JSON() which will throw an error as it is not correct
if you want to read more about JSON.parse you can visit mdn docs

Problem with ssl comuniction with post request

Hey, I built ssl communication with self certificate. The connection is working, but when I trying to deliver data on the client side with post request in postman or my android client, the body of the request in the server side is empty.
Here is my nodejs server code below,thankes for help.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const app = express()
app.use(express.json())
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))
You're reading the response body. You should look at the request.
In any case, there won't probably be much reasonable data to read unless you parse the POST payload somehow; I'd recommend the Express library rather than raw Node.js HTTP bits if you don't want to do that yourself.
here is my answer for my question,like AKS said, you need to parse the post request, i add bodyparser to my code and it worked.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.urlencoded({ extended: true })) // <==== parse request body as JSON
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))

ExpressJS application to get Instagram media works on locahost and not on Firebase Functions

I will explain the problems in more detail.
I'm trying to do a really simple little practice. Through a link, the ID of an Instagram post is passed as a parameter.
After this, '? __ a = 1' is added to the URL for subsequent data processing once the JSON object has been obtained.
On localhost this works fine and I get the JSON object. But once deployed as a function in Firebase, although it accepts the request without errors, it does not return a JSON object. Instead it returns HTML content, like this:
"<!DOCTYPE html>\n<html lang=\"en\" class=\"no-js not-logged-in client-root\">\n <head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\n <title>\nLogin • Instagram\n</title>\n\n
....
Does anyone know what is causing this problem?
...
Localhost:
Deployed like a Firebase Function:
I briefly attach the code of my application.
index.js
const functions = require('firebase-functions');
const server = require("./src/server");
const d = functions
.runWith({
memory: "2GB",
timeoutSeconds: 120
})
.https
.onRequest(server);
module.exports = {d};
server/index.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app
.use(cors({origin: true}))
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: false}))
.use("/", require("./route"))
.get('*', (_, res) =>
res.status(404)
.json({success: false, data: "Endpoint not found"}));
module.exports = app;
server/route.js
const router = require("express").Router();
const controller = require("./controller");
router.get("/:url", controller.getImageVideo);
module.exports = router;
server/controller.js
'use strict'
const axios = require('axios');
async function getImageVideo(req, res) {
const URL_id = req.params.url;
const URL = 'https://www.instagram.com/p/' + URL_id + '?__a=1';
const metadata = await axios.get(URL);
const test = metadata.data;
return res
.json({
test
});
}
module.exports = {
getAllLanguages,
getImageVideo
}

response object is undefined, of post method function

this is simple demo, making http post request and tries the log request object;
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var router = express.Router();
app.use(router)
app.use(bodyParser.json())
foo=(req, res)=>{
console.log(req.body)
res.send('Request Handled Here!')
}
router.route('/').post(foo)
app.listen(3300, '127.0.0.1', (req, res)=>{
console.log("Express listening!!!!")
});
I can see data "Request Handled Here" message but return data is undefined always in the console, I couldn't figure why "req" object is undefined out.
Edited: I am using postman to test api, content-type:application/json and there is {message:"hello world!"} dummy data in Body section
Edited2: it seems my only issue there is no "body" attribute in request context, it retrieves all req header but I just want to get posted data, many samples on net contains req.body section whats wrong here?
The problem in middleware declaration order. router must be added after body-parser:
var app = express()
var router = express.Router();
app.use(bodyParser.json());
app.use(router);

Resources