Integrate Express.js-REST-Endpoint with Meteor App

2020-02-15 06:43发布

问题:

I have a kinda tricky situation: I'm currently building a full meteor-featured application. But I also need to expose some functionality as REST-Service for automation reasons (a third party application should be able to insert and receive data via REST).

The express.js-package seems to be a very solid option for building a REST-Endpoint into a node.js environement but I'm wondering how to integrate this endpoint into meteor.

What I want is to access the "normal" Site via for example http://myfancysite.com/my-display-route and at the same time be able to access my REST-Endpoint via for example http://myfancysite.com/api/insert-crazy-data/.

The "normal" Site is accessible via the port defined when starting Meteor. The thing is, that I have to specify a different port for express.js to listen on and I want both - meteor and express - to share the same port since I don't want to access the REST-Endpoint on a different port.

Is this somehow possible? :D

Here's some code I use for express at the moment.

//<meteor-root>\server\main.jsx

import { Meteor } from 'meteor/meteor';

// do some meteor things
...

//require express
var express = require('express');

//create application
var app = express();

//use environement defined port or 3000
var port = process.env.PORT || 3000;

//create router
var router = express.Router();

//define routes
...

//register all routes with '/api'
app.use('/api', router);

//start server
app.listen(port); // <= this should be the same port as the meteor application itself!
console.log('listening on port ' + port);

回答1:

Meteor is essentially a node app that already exposes a connect http server, which means you can define server routes simply like:

import { WebApp } from 'meteor/webapp';

WebApp.connectHandlers.use('/hello', (req, res, next) => {
  res.writeHead(200);
  res.end('Hello world from your server');
});

If you insist on using express, then you can register your express routes as connect middleware like so:

import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import express from 'express';

const app = express();

app.get('/api', (req, res) => {
  res.status(200).json({ message: 'Hello from Express!!!'});
});

WebApp.connectHandlers.use(app);

Et voilà!