0
votes
    // this is app.js which is the main application file
    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');

    var api = require('./routes/api');``
    //var users = require('./routes/users');

    var app = express();

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

  //  app.use('/', routes);
    app.use('/api', api);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
        app.use(function(err, req, res, next) {
            res.status(err.status || 500);
            res.render('error', {
                message: err.message,
                error: err
            });
        });
    }

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });


    module.exports = app;

and this is api.js which implements the RESTful API.Post is a resource and because of this we will implement a /posts API which will First we'll implement placeholder route handlers for the /posts api within api.js.

var express = require('express'); var router = express.Router();

//api for all posts
router.route('/posts')

    //create a new post
    .post(function(req, res){

        //TODO create a new post in the database
        res.json({message:"TODO create a new post in the database"});
    })

    .get(function(req, res){

        //TODO get all the posts in the database
        res.json({message:"TODO get all the posts in the database"});
    })



module.exports = router;

i am getting this on postman

2

2 Answers

2
votes

You should be going to

http://localhost:3000/api/posts

Not

http://localhost:3000/routes/api/posts

..

Edit:

I didn't realize you're trying to call

req.send

Well that is not a method of

req (request)

You're looking for

res (response)

And on top of that you're trying to send a json result, not plain text so use

res.json 

Instead of

res.send

0
votes

I don't see you starting the server with app.listen(3000). You merely export the express app.

Or is there a different module that spins up the server?