I am a newbie at mean stack development. I was trying to create an API for simple user registration and got stuck with a 404 error.
Here are my code files
package.json
{
"name": "userStory",
"version": "1.0.0",
"description": "This is a user story App",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Arindam Dawn",
"license": "ISC",
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "^1.12.3",
"express": "^4.12.3",
"mongoose": "^4.0.2",
"morgan": "^1.5.2"
}
}
user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
name : String,
username : {type: String, required: true, index: {unique: true}},
password : {type: String, required: true, select: false}
});
UserSchema.pre('save', function(next){
var user = this;
if(!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash){
if(err) return next(err);
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function(password){
var user = this;
return bcrypt.compareSync(password, user.password);
}
module.exports = mongoose.model('User', UserSchema);
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('/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'});
});
});
return api
}
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){
if(err){
console.log(err);
}else{
console.log("Connected to the database");
}
});
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('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
app.listen(config.port,function(err){
if(err){
console.log(err);
}else{
console.log("Listening on port 3000");
}
});
config.js
module.exports = {
"database" : "mongodb://root:abc123@ds045531.mongolab.com:45531/userstory",
"port" : process.env.PORT || 3000,
"secretKey" : "addyrockz"
}
Here is my directory structure
userStory
-app
-models
-user.js
-routes
-api.js
-node_modules
-public
-index.html
config.js
package.json
server.js
I am trying to check the API using postman client. I tried the url localhost:3000/api/signup using post and url-encoded.
I passed the three fields as name, username and password with their respective values but i am recieving 404 error.
Aucun commentaire:
Enregistrer un commentaire