Rju
Rju

Reputation: 63

The routing of my express app does not work

I am trying to most optimally structure the files of my Express app. And the Router module confuses me.

As far as I know, all queries should be in models folder.

This is my current desired setup (which does not work for my query.js and query2.js files, the error I get is that "App" is not defined). When I put the query code (from query.js file) inside my App.js file directly, then it works however.

Also the setup I have works correctly for my Email routing.

How to fix?

Here my project structure:

project_structure

Here content of my files:

APP.JS

const express = require('express');
const request = require('request');
const requestPromise = require('request-promise');
const bluebird = require('bluebird');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

app.use(cors());

const router = require('./routes'); 
app.use(router);

function App(req, res) {
  if (!req.url) {
    req.url = '/';
    req.path = '/';
  }
  return app(req, res);
}

module.exports.my_server = App;

INDEX.JS (in routes folder)

const express = require('express');
const router = express.Router();
const config = require('../config');

let email = require('../models/email');

const query = require("../models/query");
const query2 = require("../models/query2");

router.post('/api/subscribe', function (req, res) {
  const data = {
    subscribed: true,
    address: req.body.email,
  };
...

module.exports = router;

QUERY.JS (in models folder)

app.get('/query', function(req, res, next) {
    request({
      uri: 'https://queryapi.api/search?q=stuff&api-key=api_key',
      qs: {
        api_key: 'api_key',
      }
    }).pipe(res);
  });

Upvotes: 0

Views: 114

Answers (2)

Tyro Hunter
Tyro Hunter

Reputation: 755

You don't have access to the variable app from your query.js. You would want to export your methods from query.js instead so you can import them to your router like this:

EDIT: change http verb from .get to .post

replace:

app.get('/query', function(req, res, next) {

with

exports.post = function(req, res, next) {

and this is how you would assign the exported method query.post to route /api/subscribe/query

const query = require("./query");

router.post('/api/subscribe/query', query.post);
/* more end points below: */
// router.get(...
// router.put(...
//  ...and so on

POST request on /api/subscribe/query

P.S: This works but things can quickly get ugly if you have more routes so it would be more maintainable if you restructure your source such that the main routes are expressed clearly in your app entry file; But that's another concern.

Upvotes: 1

Ashikur Rahman
Ashikur Rahman

Reputation: 78

In index.js add this line.

router.use(query)

Upvotes: 0

Related Questions