Trouble with using webapp with Meteor app - everything blank?

Hi, I’m trying to build an app that can work as usual as a meteor app, but can also receive requests on /api/receive. My server code below seems to overwrite my whole meteor app so nothing appears in the browser - everything is just blank on /

Is it possible to use Webapp with meteor and also use meteor as normal at the same time?

import { WebApp } from 'meteor/webapp';

WebApp.connectHandlers.use('/api/receive', bodyParser.urlencoded({ extended: false }));

WebApp.connectHandlers.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
  console.log('called');

  Meteor.call('msgSent', req.body, (error, result) => {
    if (error) {
      console.log("err")
      res.end();
    } else {
      console.log(result);
      res.writeHead(200, {'Content-Type': 'text/xml'});
      res.end(`
        <TextMsg>
          ${result}
        </TextMsg>
      `);
    }
  });
});

Seems to work when I do:

WebApp.connectHandlers.use(bodyParser.urlencoded({ extended: false }));

WebApp.connectHandlers.use('/api/receive', (req, res, next) => {..

This line:

WebApp.connectHandlers.use((req, res, next) => {

Because it doesn’t have a route parameter will apply to every request sent to the server.

Your solution:

WebApp.connectHandlers.use(bodyParser.urlencoded({ extended: false }));

WebApp.connectHandlers.use('/api/receive', (req, res, next) => {..

Partially fixes this, but now applies bodyParser to every request sent to meteor.
What you want is to scope both to the routes to which they apply:

WebApp.connectHandlers.use('/api/receive', bodyParser.urlencoded({ extended: false }));

WebApp.connectHandlers.use('/api/receive', (req, res, next) => {..

If you’re planning on adding more apis that require bodyParser, you can also scope it to /api/ and it will match all routes that start with that

1 Like