简体   繁体   中英

Can't get a response from my server. Why?

I can't get a response from my server. I am using postman and running the following post request:

localhost:4000/users/register?email=test@gmail.com&f_name=testf&s_name=tests&password=test

It hangs for a very long time and then says:

Could not get any response

This is my code:

[user.route.js]
const express = require('express');
const userRoutes = express.Router();
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

//require User model in the routes module
let User = require('../models/user.model.js');

//Make router use cors to avoid cross origin errors
userRoutes.use(cors);

//secret
process.env.SECRET_KEY = 'secret';

//define register route
userRoutes.post('/register', (req, res) => {
  const today = new Date();
  const userData = {
    email: req.body.email,
    f_name: req.body.f_name,
    s_name: req.body.s_name,
    password: req.body.password,
    created: today
  }
  //Find one user based on email, hash their password and then create a document in the collection for that user
  User.findOne({
      email: req.body.email
    })
    .then(user => {
      if (!user) {
        bcrypt.hash(req.body.password, 10, (err, hash) => {
          user.password = hash;
          User.create(userData)
            .then(user => {
              res.json({
                status: user.email + ' registered'
              });
            })
            .catch(err => {
              res.send('error: ' + err);
            });
        });
      }
    });
});

userRoutes.post('/login', (req, res) => {
  User.findOne({
      email: req.body.email
    })
    .then(user => {
      if (user) {
        if (bcrypt.compareSync(req.body.password, user.password)) {
          const payload = {
            _id: user._id,
            f_name: user.f_name,
            s_name: user.s_name,
            email: user.email
          }
          let token = jwt.sign(payload, process.env.SECRET_KEY, {
            expiresIn: 1440
          });
          res.send(token);
        } else {
          res.json({
            'Error': 'Password Incorrect'
          });
        }
      } else {
        res.json({
          'Error': 'User does not exist'
        });
      }
    })
    .catch(err => {
      res.send('Error: ' + err);
    });
});

module.exports = userRoutes;

[user.model.js]
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let User = new Schema({
  email: {
    type: String
  },
  f_name: {
    type: String
  },
  s_name: {
    type: String
  },
  password: {
    type: String
  },
  created: {
    type: String
  }
}, {
  collection: 'users'
});

[server.js]
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./db.js');

mongoose.Promise = global.Promise;
mongoose.connect(config.DB, {
  useNewUrlParser: true
}).then(
  () => {
    console.log('Database is connected')
  },
  err => {
    console.log('Can not connect to the database' + err)
  }
);

app.use(cors());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

var Users = require('./routes/user.route');

//make /users use routes
app.use('/users', Users);

app.listen(PORT, function() {
  console.log('Server is running on Port:', PORT);
});

[db.js]
module.exports = {
  DB: 'mongodb://localhost:27017/pharaohcrud'
}

I'm using Node, MongoDB, Mongoose, Vue, Express.

I'm new to Node in general so it's hard for me to give details on what i've done. Please feel free to ask any questions that you need answered to help me with issue and ill answer as thoroughly as i can :)

EDITS:

Here is the updated db.js file

module.exports = {
  DB: 'mongodb://localhost:27017/pharaoh'
}

Here is the updated post request that im sending to the server through postman:

localhost:4000/users/register

[raw json request]
{
    "email": "test@gmail.com",
    "f_name": "test",
    "s_name": "test",
    "password": "test"
}

You have to send json data with your post request not query strings.

In postman, select "Body" tab and choose "raw" and from the dropdown menu select "json" format. Send your user data as Json, this will solve the issue.

Image description here

I went deleted all database-related code and retyped it, and now it works. I guess the lesson here is to always pay attention while typing code to make sure you're writing it correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM