1

I built a code to create a server with node.js, express.js and mongodb. It's a simple code to save user data to mongodb. I tested this code with Advanced REST Client.

At that moment, the request parameters are transferred but have 0 request error when send the request with this url: http://localhost:8080/users.

server.js

var express     = require('express');
var app         = express();
var port        = process.env.PORT || 8080;
var morgan      = require('morgan');
var mongoose    = require('mongoose');
var User        = require('./user');
var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(morgan('dev'));

mongoose.createConnection('mongodb://localhost:27017/mean', function(err) {
    if (err) {
        console.log('Not connected to the database: ' + err);
    } else {
        console.log('Successfully connected to MongoDB')
    }
});

// http://localhost:8080/users
app.post('/users', function(req, res) {
    var user = new User();
    user.username = req.body.username;
    user.password = req.body.password;
    user.email = req.body.email;
    if (req.body.username == null || req.body.username == "" || req.body.password == null || req.body.password == "" || req.body.email == null || req.body.email == "") {
      res.send("Ensure username, email and password were provided");
    } else {
        user.save(function(err) {
            if (err) {
                res.send("Username or Email already exists.");
            } else {
                res.send("user created");
            }
        });
    }
});

app.listen(port, function() {
    console.log('Running the server on port ' + port);
});

user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var UserSchema = new Schema({
    username: { type: String, lowercase: true, required: true, unique: true },
    password: { type: String, required: true },
    email: { type: String, required: true, lowercase: true, unique: true }
});

UserSchema.pre('save', function(next) {

    var user = this;
    bcrypt.hash(user.password, null, null, function(err, hash) {
        if (err) return next(err);
        user.password = hash;
        next();
    });
});

module.exports = mongoose.model('User', UserSchema);

package.json

{
  "name": "mean",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "^2.18.2",
    "express": "^4.16.2",
    "mongoose": "^4.13.7",
    "morgan": "^1.9.0"
  }
}
1

2 Answers 2

1

You should be doing a post request instead of a get request with your browser.

Also

var user = new User();
    user.username = req.body.username;
    user.password = req.body.password;
    user.email = req.body.email;
    if (req.body.username == null || req.body.username == "" || req.body.password == null || req.body.password == "" || req.body.email == null || req.body.email == "") {
      res.send("Ensure username, email and password were provided");

You are not sending any parameters like email or name, ... in your request. So nothing can be saved in your database.

Do post request instead of get and consider adding the correct parameters in your request and everything will be fine.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your response. But I used post method in the Advanced REST Client. You can test with this url: localhost:8080/users
@OleksandrLesnevskyi, if you are using a post, are you sending the parameters username, password and email in your request ?
Sure. I send the parameters in json format like this. { "username":"creation", "password":"qwer","email":"[email protected]"
@OleksandrLesnevskyi, you sent the request parameters. Are you able to retrieve those parameters in your server? If not do you have an error ?
0

In server.js use this code to connect to MongoDB

mongoose.connect('mongodb://localhost:27017/mean', function(err) {
    if (err) {
        console.log('Not connected to the database: ' + err);
    } else {
        console.log('Successfully connected to MongoDB')
    }
});

Mongo DB saves Object:

enter image description here

enter image description here

1 Comment

Thanks for your answer. Your answer was very helpful.

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.