kodokbuncit
kodokbuncit

Reputation: 43

need help about node.js router

I have some question about nodejs routers this is my code:

server.js

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config');
var mongoose = require('mongoose');

var app = express();

mongoose.connect(config.database, function (err){
    // body...
    if(err){
        console.log(err);
    }else{
        console.log('database ok')
    }
});

app.use(bodyParser.urlencoded({ extend: true }));
app.use(bodyParser.json());
app.use(morgan('dev'));

//call api
var api = require('./app/routes/api')(app, express);
api.use('/api', api);


app.get('/',function(req,res){
    res.sendFile(__dirname + '/public/views/index.html')
});


app.listen(config.port, function (err) {
    // body...
    if (err) {
        console.log(err);
    }else{
        console.log('listen in port ' + config.port)
    }
})

api.js

var User = require('../models/user');
var config = require('../../config');
var secretKey = config.secretKey;



module.exports = function(app, express) {

    var api = express.Router();

    api.post('/daftar', function (req, res) {
        var user = new User({
            name: req.body.name,
            username: req.body.username,
            password: req.body.password
        });

        user.save(function (err) {
            if(err){
                res.send(err);
                return;
            }

            res.json({ message: 'user telah dibuat'});

        });

    });



    return api;
}

My problem when I try to post something using /api/daftar url the responce is cannot be found, but when I try move my api.post() to my server.js it works. I just changed api.post() to app.post()

Can you tell me what I'm doing wrong?

Upvotes: 0

Views: 62

Answers (1)

michaelgmcd
michaelgmcd

Reputation: 2439

Possible solution 1

Change api.use('/api', api) to app.use('/api', api)

If that doesn't work, I've included the way I would do it below in

Possible solution 2

By the looks of it, you are using express 4.x. Give this a try.

server.js

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config');
var mongoose = require('mongoose');

var app = express();

...

var api = require('./app/routes/api')(app); // Don't need to pass express here
app.use('/api', api); // Note the app.use instead of api.use

...

api.js

var User = require('../models/user');
var config = require('../../config');
var secretKey = config.secretKey;

module.exports = function(app) {

    // Removed express and changed to app.post
    app.post('/daftar', function (req, res) {
        var user = new User({
            name: req.body.name,
            username: req.body.username,
            password: req.body.password
        });

        user.save(function (err) {
            if (err) {
                console.log(err);
                // Set an error status code here
                res.status(400).send(err);
            }

            // I prefer this syntax. More verbose and you can set the HTTP status code
            // Could put in directly, but I abstracted the msg to a variable here.
            var msg = { message: 'user telah dibuat' };
            // 201 means Created
            res.status(201).send(msg);
        });

    });

    // Do not need to return anything        

}

It is difficult for me to test this, but if you have some additional problems, add some console.log() calls in your app.post block to make sure it's being called.

Upvotes: 2

Related Questions