3gwebtrain 3gwebtrain - 4 months ago 27
Node.js Question

`express` - app chrome postman giving always error instead of response

Please some one help me to find the issue here:

When i am trying to post my

username
and
password
i am always getting error as :
requester.js:6211 POST http://localhost:7000/api/login 403 (Forbidden)send @ requester.js:6211(anonymous function) @ requester.js:4811dispatch @ jquery.min.js:3i @ jquery.min.js:3
requester.js:1056 Defining mode


i don't know what is the issue here at all.
here is the post man request screen shot :

enter image description here

here is my api file :

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

var secretKey = config.secretKey;

var jsonwebtoken = require("jsonwebtoken");


function createToken ( user ) {

var token = jsonwebtoken.sign({
_id : user.id,
name : user.name,
username: user.username
}, secretKey, {
expiresIn : "1440m"
})

return token;
}

module.exports = function( app, express ) {

var api = express.Router();

api.post('/signup', 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 has been created!"});
});

api.get('/users', function( req, res ) {

User.find({}, function( err, users ) {

if( err ) {
res.send( err );
return;
}

res.json( users );

})

});

api.post('/login', function( req, res ) {

User.findOne({
username : req.body.username
}).select('password').exec(function( err, user ) {

if( err ) throw err;

if(!user) {
res.send({ message : "User doesnt Exist!"})
} else if( user ) {

var validPassword = user.comparePassword( req.body.password );

if(!validPassword) {
res.send({ message : "Invalid Password"});
} else {

var token = createToken( user );

res.json({
success : true,
message : "Successfuly loged In!",
token : token
})

}
}

})

})

});

//middleware

api.use(function(req, res, next) {


console.log("Somebody just came to our app!");

var token = req.body.token || req.param('token') || req.headers['x-access-token'];

// check if token exist
if(token) {

jsonwebtoken.verify(token, secretKey, function(err, decoded) {

if(err) {
res.status(403).send({ success: false, message: "Failed to authenticate user"});

} else {
req.decoded = decoded;
next();
}
});
} else {
res.status(403).send({ success: false, message: "No Token Provided"});
}

});

//Destination B

api.get("/", function( req, res ) {

res.json("Hello World!");

})

return api;

}

Answer

The route should be 'api/signup' and not only '/signup'.

The route definitions are not right. Instead of:

 api.post('/signup', function( req, res ) {
...
        api.get('/users', function( req, res ) {
   })
})

it should be:

 api.post('/signup', function( req, res ) {
...
})
api.get('/users', function( req, res ) {
...
})
Comments