API请求后,节点服务器未返回任何响应

时间:2018-08-14 12:43:04

标签: mysql node.js express sequelize-cli

我正在使用Node.js,Express,MYSQL并借助sequelize构建API。我正在使用MVC模式。

但是,我遇到的问题是服务器无法在请求后发回任何http响应。例如,通过邮递员发送发帖请求时,该请求会继续加载,并且会在大约2分钟后以“可能无法获得任何响应”异常终止。发生这种情况时,数据已正确保存在数据库中。

这是我的AuthController用户注册方法:

'use strict';
// AuthController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
const Model = require('../models/index');
const User = Model.sequelize.import('../models/user');


// Register new User.
exports.register = function(req, res) {
        var hashedPassword = bcrypt.hashSync(req.body.password, 8);

     User.create({
     name : req.body.name,
    email : req.body.email,
    password : hashedPassword
        }, 

function (err, user) {
    if (err) 
    {
      return res.status(500).send("There was a problem registering the user. "+err)
    }
    else{
      // create a token
    var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
      expiresIn: 86400 // expires in 24 hours
    });
    res.status(200).json({ auth: true, token: token }); 
    }



  }); 

};

// App.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
var app = express();
var indexRoutes = require('./routes/index');
var userRoutes = require('./routes/users');
var courseRoutes = require('./routes/courses');
var authRoutes = require('./routes/auth');

// view engine setup
// Currently I am not using view-templates
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());
app.use(cors()); //enable CORS
app.use(express.static(path.join(__dirname, 'public')));

//User Routes
app.use('/', indexRoutes);
app.use('/api', userRoutes);
app.use('/api', courseRoutes);
app.use('/api/auth', authRoutes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

//路线

// auth.js

var express = require('express');
var router = express.Router();
//Require Controller Modules
var controller = require('../controllers/AuthController');

//Register new user

router.post('/register', controller.register);
router.get('/user', controller.me);

router.post('/login', controller.login);
router.get('/logout', controller.logout);


module.exports = router;

//用户模型

'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    //id: DataTypes.INTEGER,
    name: DataTypes.STRING,
    email: {type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: {msg: "Invalid Email"} }},
    password: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here

  };
  return User;
};

数据库连接//在models / index.js中

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(__filename);
var env       = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db        = {};
const Op = Sequelize.Op;

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {

  var sequelize = new Sequelize(config.database,
   config.username,
    config.password, 

     { 
  host: config.host,
  dialect: config.dialect,
  operatorsAliases: false, 
    }
  );


  //check if connection is established
  sequelize
  .authenticate()
  .then(() => {
    console.log('Database Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

我认为我犯了某些错误或遗漏了一些错误。发送POST请求时遇到此问题。数据保存在mysql表中,但没有响应发回。

请协助。谢谢。

1 个答案:

答案 0 :(得分:0)

谢谢你们为我们提供的帮助。解决后,我发现问题出在控制器方法上。数据保留在数据库中之后,它的结构方式没有发送回响应。 这就是我在 AuthController 中重新编码注册方法的方式:

//旧的

// Register new User.
exports.register = function(req, res) {
        var hashedPassword = bcrypt.hashSync(req.body.password, 8);

     User.create({
     name : req.body.name,
    email : req.body.email,
    password : hashedPassword
        }, 

function (err, user) {
    if (err) 
    {
      return res.status(500).send("There was a problem registering the user. "+err)
    }
    else{
      // create a token
    var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
      expiresIn: 86400 // expires in 24 hours
    });
    res.status(200).json({ auth: true, token: token }); 
    }

//重写:

// Register new User.
exports.register = function(req, res) {
        var hashedPassword = bcrypt.hashSync(req.body.password, 8);

     User.create({
     name : req.body.name,
    email : req.body.email,
    password : hashedPassword
        })
        .then(user=>{
           // create a token
    var token = jwt.sign({ id: user._id }, config.secret, {
      expiresIn: 86400 // expires in 24 hours
    });
    return res.status(200).json({ auth: true, token: token });

        }).catch(err=>{


          return res.status(500).send("There was a problem registering the user. "+err)

        }); 



};

这对我有用,代码现在按预期工作。