Almin Islamovic Almin Islamovic - 6 months ago 18
Node.js Question

API post issue with Express

Im having an issue where I get a 404 error when posting to my route.

This is my code:

app.js

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 routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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('/users', users);

// 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;


api.js

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Page= require('../models/page.js');
var adminUser= require('../models/admin-users.js');
var bodyParser = require('body-parser').json();
var bcrypt = require('bcrypt-nodejs');
/* User Routes. */

router.get('/', function(req, res) {
res.send('Welcome to the API zone');
});

router.get('/pages', function(request, response) {

return Page.find(function(err, pages) {
if (!err) {
return response.send(pages);
} else {
return response.send(500, err);
}
});
});

//Post method, creates new Page object
router.post('/pages/add',bodyParser, sessionCheck, function(request, response) {


var page = new Page({
title: request.body.title,
url: request.body.url,
content: request.body.content,
menuIndex: request.body.menuIndex,
date: new Date(Date.now())
});

page.save(function(err) {
if (!err) {
return response.send(200, page);

} else {
return response.send(500,err);
}
});
});


router.post('/pages/update',bodyParser, sessionCheck, function(request, response) {
var id = request.body._id;

Page.update({
_id: id
}, {
$set: {
title: request.body.title,
url: request.body.url,
content: request.body.content,
menuIndex: request.body.menuIndex,
date: new Date(Date.now())
}
}).exec();
response.send("Page updated");
});

// id rem
router.get('/pages/delete/:id', bodyParser, sessionCheck, function(request, response) {
var id = request.params.id;
Page.remove({
_id: id
}, function(err) {
return console.log(err);
});
return response.send('Page id- ' + id + ' has been deleted');
});


// -----
router.get('/pages/admin-details/:id', bodyParser, sessionCheck, function(request, response) {
var id = request.params.id;
Page.findOne({
_id: id
}, function(err, page) {
if (err)
return console.log(err);
return response.send(page);
});
});

router.get('/pages/details/:url', function(request, response) {
var url = request.params.url;
Page.findOne({
url: url
}, function(err, page) {
if (err)
return console.log(err);
return response.send(page);
});
});


// 404 error

router.post('/add-user', function(request, response) {
var salt, hash, password;
password = request.body.password;
salt = bcrypt.genSaltSync(10);
hash = bcrypt.hashSync(password, salt);

var AdminUser = new adminUser({
username: request.body.username,
password: hash
});
AdminUser.save(function(err) {
if (!err) {
return response.send('Admin User successfully created');

} else {
return response.send(err);
}
});
});

router.post('/login', function(request, response) {
var username = request.body.username;
var password = request.body.password;

adminUser.findOne({
username: username
}, function(err, data) {
if (err | data === null) {
return response.send(401, "User Doesn't exist");
} else {
var usr = data;

if (username == usr.username && bcrypt.compareSync(password, usr.password)) {

request.session.regenerate(function() {
request.session.user = username;
return response.send(username);

});
} else {
return response.send(401, "Bad Username or Password");
}
}
});
});

router.get('/logout', function(request, response) {
request.session.destroy(function() {
return response.send(401, 'User logged out');

});
});

function sessionCheck(request,response,next){

if(request.session.user) next();
else response.send(401,'authorization failed');
}

module.exports = router;


The issue is with the
router.post('/add-user', function(request, response) {


Is there any more information you need?

Also i Tried adding bodyparser
router.post('/add-user', bodyParser, function(request, response) {


Thanks for any help!

Answer

You are missing those lines :

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

I would even recommend you to do the following :

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

router.get('/', function(request, response)
router.get('/pages', function(request, response)
router.post('/pages/add', function(request, response)

That way, you won't have 2 different requests being redirected to the same route

Comments