Using Express and Body-Parser in a Google Cloud Function (NOT Firebase Cloud Function) - express

I am trying to get my head around using GCF and Express together. All of the examples I have found give good info about Firebase CF but not straight up GCF.
Specifically, I need to use body-parser to get at some POSTed body info that is being sent via a content-type of 'x-www-form-urlencoded' rather than 'application/json'. I can see the data if I console.log the req.rawBody but haven't found a clean way to get at the body parts.
I found this article: https://mhaligowski.github.io/blog/2017/05/15/serving-functions-express.html but to me it is just a couple of code snippets that really isn't clear on how things actually hang together.

You can require body-parser and as long as you send the Content-Type: application/json header, it will parse as JSON automatically:
const bodyParser = require('body-parser');
exports.acceptJson = (req, res) => {
console.log(req.body);
res.status(200);
};

Related

How to handle backend auth with express as reverse proxy api

I am using express the first time in a project as a kind of reverse proxy in between my frontend and backend. The backend authentication is cookie based.
First I was using http-proxy-middleware to make my requests. This works fine and the cookie gets passed no problem.
The problem is that I want to decouple the front and backend as the api isn't very usable right now (for example 3 requests necessary to get data for one view). So instead of making requests directly I want to have my express server handle the heavy lifting in the background.
Currently I am using axios for the requests and pass the cookie through with the request and the new one back with the response. This works fine but feels very hacky and error prone. For example I have to split the returned setcookie string in a very weird way.
app.get('/api/myrequest', (req, res) => {
axios.get('backendserver/url', {
headers: {
Cookie: req.cookies['auth'],
},
responseType: 'json',
})
.then((response) => {
let tempCookie = response.headers['set-cookie'][0];
tempCookie = tempCookie.split(';')[0];
tempCookie = tempCookie.split('=');
res.cookie(tempCookie[0], tempCookie[1]);
res.send(response.data);
})
});
I suppose there is a much better way to handle this. I was looking at things like passportjs but am not sure if it fits this special use case as the auth isn't handled by express itself.
Maybe someone can point me in the right direction?

Express JS modules to parse form-data text from Postman

I have just 3 variables and posting using postman to sever.
I need a solution to parse just form-data text in Express JS
When I searched in net, I see people just suggested that,
We cant use body-parser to handle form-data and need to use multer, busboy, multiparty
Also people suggest if not sending files need not use multer and formidable.
But can anyone explain how exactly to use this with node js. When I see modules github, i am not able to understand to use it for my needs.
https://stackoverflow.com/a/36199881/5078763
I know setting x-www-form-urlencoded option in postman works but I need for form-data
app.post('/addUsrForm', addUsrFnc);
function addUsrFnc(req, res)
{
console.log("Data Received : ");
var namUserVar =
{
nameKey: req.body.nameKey,
mailKey: req.body.mailKey,
mobileKey: req.body.mobileKey
};
console.log(NquUsrJsnObjVar);
}
This answer provides good detailing of the different use cases for html form encoding. What does enctype='multipart/form-data' mean?
x-www-form-urlencoded is the default.
multipart/form-data is for larger data sends, such as entire files.
Postman settings aside, if your server needs to handle multipart/form-data, install multer and use it like so...
if just sending text fields in a multipart/form-data encoding:
var multer = require('multer')
var multParse = multer()
...
function handler(req, res) {
// fields will be parsed in req.body
}
...
app.post('/', multParse.none(), handler)
Follow the multer api on the multer github page if you actually are sending files and not just text fields.

How to send a POST request response back to client (React component)?

I'm using React to send a post request to my express server which then returns a response, like so:
app.post('/api/games', function(req, res) {
return res.json();
});
Before I use that response to persist it to a database, I want to be able to see everything within that response. When I console.log it from the server, I get a long list of the JSON object printed, but would ideally like something closer to Chrome's dev tools console where I can click through and inspect everything. How can I send this response JSON back to my React component so that I can console.log it in in the browser?
Thanks!
You can use node-inspector in order to debug your express API.
It uses Chrome Dev Tools so you'll feel like you are debugging your client side!
Remember, a request comes in, and the response goes out.
on a request, the req.body and req.params will contain the body/params of the request.
To respond to a request, use the res.json({someJSONHere}) or you can also res.send({someJson})
You can also console.log inside the server and watch output on the terminal
app.post('/api/games', function(req, res) {
console.log(req.params)
console.log(req.body)
return res.json(
Object.assign({}, req.body, req.params)
);
});
Express request/response Documentation
If you want to view your response in the client-tier here are some of the things you can do using the GoogleChrome asides from the console
1 Use React Developer Tools
2 I like using Postman for viewing and manipulating request/response

Unobtrusive middle-ware for Expres.js to inspect request body

Does there exist a thirdparty middleware or a way to create such middleware for Express.js that allows for intercepting all requests and inspecting the request's body content without affecting subsequent middleware such as bodyParser or route endpoints which may rely on the raw body such as express-http-proxy?
From what I can tell bodyParser itself seems to work in a somewhat obtrusive way that does not allow a route to override the default parsing behavior. The express documentation describes how request.body is filled in by middleware such as bodyParser. This behavior of bodyParser makes sense from simplicity and performance perspective but doesn't make it a great candidate for creating middleware which needs to inspect the contents of a request and let the remaining portion of the app working without modification. This is especially true seeing that depending on the parsing middleware the results may be in entirely different formats. After some digging I'm left wondering if it's generally possible to pull this off with express or perhaps once you read the request body you eliminate the ability to make use of further middleware such as bodyParser or express-http-proxy which expect to access the body directly.
Possibly related:
express req.pipe() does not work
You could always use the raw-body package with express middleware like so:
var getRawBody = require('raw-body');
var typer = require('media-typer');
app.use(function (req, res, next) {
getRawBody(req, {
length: req.headers['content-length'],
limit: '1mb',
encoding: typer.parse(req.headers['content-type']).parameters.charset
}, function (err, string) {
if (err) return next(err)
req.text = string
next()
})
})
If your only concern is performance, I wouldn't worry too much about body-parser as it's unlikely to have a massive performance impact. If you can, I'd suggest you just use body-parser with a typical express middleware app.use(..) to inspect the request body.

Can I use multiparty for a single route in my express app?

I have an Express 3 app that uses bodyParser for most routes. (Most routes only accept multipart.) I have a single route that is going to be parsing files up to 1GB in size which bodyParser can't seem to handle. I would like to use multiparty for only this route so I don't have to rewrite the whole API. Is this possible?
You can supply middleware to a single route by doing this:
var multipartyMiddleware = function (req,res,next){
//put your code to parse multipart here and call "next" when done
}
app.post('/this/is/a/single/route', multipartyMiddleware, function(req,res){
//do normal business logic in this route and send the response
})
If you need to bypass the multipart parsing in the old bodyParser in express 3 you can replace this:
app.use(express.bodyParser())
with this:
app.use(express.json())
app.use(express.urlencoded())
This works because the source of the bodyParser middleware reveals that it is just a combo of three middleware parsers: multipart, json, and urlencoded.
see the connect 2.X source here: https://github.com/senchalabs/connect/blob/2.x/lib/middleware/bodyParser.js#L54