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

node server not returning any response after API request

我正在使用 Node.js、Express、MYSQL 并在 sequelize 的帮助下构建一个 API。我正在使用 MVC 模式。

但是我遇到的问题是服务器无法在请求后发回任何 http 响应。例如,当使用 postman 发送 post 请求时,请求会继续加载并在大约 2 分钟后终止,并出现 COULD NOT GET ANY RESPONSE exception。发生这种情况时,数据已正确保存在数据库中。

这是我的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 table 中,但未发回任何响应。

请协助。谢谢。

感谢你们的帮助。解决后,我发现问题出在控制器方法上。它的结构方式是在数据保存在数据库中后不发回响应。 这就是我在 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)

        }); 



};

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