无法从我的服务器获得响应。为什么?

时间:2019-03-29 17:02:21

标签: node.js mongodb express mongoose postman

我无法从服务器获得响应。我正在使用邮递员并运行以下邮寄请求:

DECLARE @value DATETIME
SET @value = CURRENT_TIMESTAMP

INSERT INTO PS_AUDIT_PSROLEUSR (AUDIT_OPRID, AUDIT_STAMP, AUDIT_ACTN, ROLEUSER, ROLENAME, DYNAMIC_SW)
    SELECT  
        'TESTUSER', DATEADD(SECOND, ROW_NUMBER() OVER (ORDER BY A.OPRID), @value),
        'D', A.OPRID, D.ROLENAME, 'N'
    FROM 
        PSOPRDEFN A
    INNER JOIN 
        PS_AD_X_WALK B ON B.OPRID = A.OPRID
    INNER JOIN 
        PS_JOB C ON C.EMPLID = B.GH_AD_EMPLID
    WHERE 
        B.GH_AD_EMPLID <> ''
        AND C.ACTION = 'TER'
        AND A.ACCTLOCK = 0

它挂了很长时间,然后说:

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

这是我的代码:

Could not get any response

我正在使用Node,MongoDB,Mongoose,Vue,Express。

我通常是Node的新手,所以我很难提供详细信息。请随时提出您需要回答的任何问题,以尽可能全面地帮助我解决问题和不正确的问题:)

编辑:

这是更新的db.js文件

[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'
}

这是即时消息通过邮递员发送到服务器的更新后的请求:

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

2 个答案:

答案 0 :(得分:0)

您必须使用发布请求发送json数据,而不是查询字符串。

在邮递员中,选择“正文”标签,然后选择“原始”,然后从下拉菜单中选择“ json”格式。以Json的身份发送用户数据,这将解决问题。

Image description here

答案 1 :(得分:0)

我删除了所有与数据库相关的代码,然后重新输入了代码,现在它可以工作了。我想这里的教训是在键入代码时要始终注意以确保正确编写代码。