Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

app.post is not a function express node

I had all my routes in server.js but I wanted to make it modular and put into a folder called routes. I created a file called apis.js in routes folder but as I did that I get TypeError: app.post is not a function

server.js:

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

var bodyParser = require('body-parser');
var urlencode = bodyParser.urlencoded({ extended: true});

app.use(express.static('public'));

var apis = require('./routes/apis');
app.use('/', apis);

module.exports = app;

apis.js:

  module.exports = function(app){

  app.get('/', function(req, res) {
    res.send('OK');
  });

  app.post('/idea', function(req, res) {
  ...
  });

};

Also, having module.exports = app in server.js is important as I have tests running and I want a instance of app everytime.

What am I missing?

like image 641
fscore Avatar asked Feb 06 '23 10:02

fscore


1 Answers

Better approach :-

server.js

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

var bodyParser = require('body-parser');
var urlencode = bodyParser.urlencoded({ extended: true});

app.use(express.static('public'));

var apis = require('./routes/apis');
app.use('/', apis);

module.exports = app;

apis.js :-

var router = require('express').Router();
router.post('/url',function(req,res,next){
 //your code 
})

module.exports = router
like image 172
Anmol Mittal Avatar answered Feb 10 '23 23:02

Anmol Mittal