WebApp access express object

How can I access express.json() and express.urlencoded() in WebApp?

As far as I can see the WebApp.handlers export is an express router to prevent users messing with the internals.

However when sending post requests that are 'Content-Type': 'application/x-www-form-urlencoded' then the req.body is empty. Using body-parser is deprecated for express >=4.16.

Any ideas?

I haven’t tried it but I think either of these would work:

Option 1

import { WebApp } from 'meteor/webapp';

WebApp.handlers.use(WebApp.express.json());
Webapp.handlers.use(WebApp.express.urlencoded({ extended: true }));

// register your routes here
// WebApp.handlers.get(…)

Option 2

import { WebApp } from 'meteor/webapp';

const { express } = WebApp;
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// register your routes here
// app.get(…)

WebApp.handlers.use(app);

Migrating to Express in M3 is such a great feature.

Express pairs well with Meteor’s core philosophy of long-term support.

3 Likes

I’m accessing the Express api via:

const express = WebAppInternals.NpmModules.express.module

I’m using this successfully:

import bodyParser from "body-parser";

WebApp.handlers.use(bodyParser.urlencoded({extended: true}));
WebApp.handlers.use(bodyParser.json());

Are these two the same?

1 Like

I asked the AI chatbot in the Meteor 3 docs and it came back with this:

No, these two are not the same.

The first line of code:

import { WebApp } from 'meteor/webapp';
const { express } = WebApp;

This is importing the WebApp from the meteor/webapp package and then destructuring express from WebApp. This express is the Express module that has been integrated into the WebApp package as of Meteor v3, as mentioned in the migration docs.

The second line of code:

const express = WebAppInternals.NpmModules.express.module;

This is accessing the Express module directly from the WebAppInternals.NpmModules object. This is not the recommended way to access Express in Meteor v3 and later, as the WebApp package now provides a more direct and integrated way to use Express.

If the chatbot answer is correct, the Meteor 3 Docs team deserves added praise!

1 Like

Tested the first option it works. I think in the past (at some point in the beta or rc) it did not work for me, so that is why I had the other approach.