Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>servermain.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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
400 views
Welcome To Ask or Share your Answers For Others

1 Answer

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à!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...