Alex Wally
Alex Wally

Reputation: 2339

Parse Server: Custom endpoint / Express route

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?

Upvotes: 0

Views: 1441

Answers (1)

Lars de Bruijn
Lars de Bruijn

Reputation: 1518

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?');
};


You need to start your server by calling app.listen See the Hello 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.

Upvotes: 3

Related Questions