0
votes

In Parse Server, where should you put express routes? I found they only work if I put them straight in index.js, but that can't be the best place, is it?

I put this in my cloud/main.js:

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

app.listen();

app.get('/test', function(req, res) {
    console.log("working?");
    res.status(200).send('working?');
});

console.log("this file definitely runs");

My console output shows "this file definitely runs" on starting the server, but when I try to access localhost:1337/test, it just says "Cannot GET /test". Whereas if I put just the app.get('/test', ...); in index.js, it works. I suppose it's because I'm not allowed to create another express() instance, maybe there's a way to get the instance that was created in index.js?

1

1 Answers

3
votes

I realise you are asking a different question than what my answer is pointing to. In case you still actually forgot the app.listen I'll leave it below.

If you're going to export your routes to a different file you'll need to pass around the app object from your index.js to the routes file.

What I usually do is three levels of abstraction. Firstly, you have the index.js which declares the app and express instances. Then I have a seperate file, say routeDefinitions.js(I usually call this index and name the starting point after my application).

Inside routeDefinitions.js I declare the routes using the app instance from index.js resulting in the following:

app.js:

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

var routes = require('./routeDefinitions')(app);

and routeDefinitions.js:

var test = require('./test');

module.exports = function(app) {
    app.get('/test', test.working);

    return app;
};

And then have each type of object in it's own route file (say you have users, apples and cars then each of those objects has it's own routes file).

test.js:

module.exports.working = function(req, res) {
    console.log("working?");
    res.status(200).send('working?');
};


app.listenHello World example

You see This definitely runs because you are indeed processing your script, however you are not listening to requests because you forgot to start your express server.