0

So I'm trying to insert 3 strings from postman to my mongo database using the api localhost:3000/api/comment/

my database is on mongodb://localhost:27017/commentbox

and my server.js contains

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

var app = express();

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

var api = require("./app/routes/api")(app, express);

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

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

mongoose.connect(config.database, { useNewUrlParser: true },(err)=>{
    if(err){
        console.log(err);
    }else{
        console.log('Connected to DB');
    }
});



app.listen(config.port, (err) =>{ 
    if(err){
        console.log(err);
    }else{
        console.log('Listening on port:'+ config.port);
    }
});

and this is the code for my api.js

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


module.exports = function(app,express){

    var api = express.Router();

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

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

            res.json({ message: "User has commented"});
        });
    });

    return api;
}

when I try to post on postman with name, comment, date (btw this are 3 strings at the moment) I always got error 404

what should be the problem? I have followed the guide thoroughly

3 Answers 3

4

Replace this line

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

With this

app.use(‘/api’, api);
Sign up to request clarification or add additional context in comments.

Comments

0

Try switching localhost to 127.0.0.1, or http://[::1]:3000

It looks like there is a common report of this issue with 'localhost' specifically: https://github.com/postmanlabs/postman-app-support/issues/2214

1 Comment

Is 'comment' in the root?
-1

I Think You api.js module was wrong. please remove return api

2 Comments

api.use('/api', api); ^ TypeError: Cannot read property 'use' of undefin at Object.<anonymous> (A:\Project\Mean\Comme at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js: at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) new error pops out
remove api.use('/api', api); and add app.use('/api', api); Best practice keep module require your server.js very begin of the file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.