node js с продолжением. Не удалось вставить в таблицу - PullRequest
0 голосов
/ 01 августа 2020
  1. Фон

  2. При использовании nodejs версии 12.

  3. Таблица «пользователь» создается в MySQL база данных dapdb.

  4. Когда я пытаюсь записать запись в таблицу - authController - Postman отображает: "{" status ":" Success ? "," data ": {} } "

  5. В таблицу не записываются данные, что является проблемой. Файлы ниже.

сервер. js

    const dotenv = require('dotenv');
    dotenv.config({ path: './config.env' });
    const db = require('./database/db');
    const app = require('./app');
    ///////////////////////////////
    // 4. Start Server
    const port = process.env.PORT || 90;
    
    db.sequelize.sync().then(() => {
      app.listen(port, () => {
        console.log(`App running on port ${port}...`);
      });
    });
   // db.js
    const Sequelize = require('sequelize');
    const mysql = require('mysql');
    const db = {};
    const sequelize = new Sequelize(process.env.db, process.env.logonid, process.env.password, {
      host: process.env.host,
      port: process.env.dbport,
      dialect: 'mysql',
    });
    db.sequelize = sequelize;
    db.Sequelize = Sequelize;
    module.exports = db;
    //userModel.js
   const db = require('./../database/db');
    Sequelize = require('sequelize');
    const validate = require('validator');
    
    const User = db.sequelize.define('user', {
      name: {
        type: Sequelize.STRING,
        trim: true,
        required: [true, 'Please give me your name!'],
        len: [3 - 50],
      },
      email: {
        type: Sequelize.STRING,
        unique: true,
        trim: true,
        required: true,
        lowercase: true,
        validate: [validate.isEmail, 'Please provide a valid email.'],
        photo: Sequelize.STRING,
        password: {
          type: Sequelize.STRING,
          required: [true, 'Please provide a password.'],
          minlength: 8,
        },
      },
      password: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      passwordConfirm: {
        type: Sequelize.STRING,
        required: [true, 'Please provide a password confirmation.'],
      },
    });
    module.exports = User;
    // authController.js
    const db = require('./../database/db');
    const User = require('./../models/userModel');
    exports.signup = async function (req, res, next) {
      const newUser = await db.sequelize.sync().then(function () {
        User.create({
          name: req.body.name,
          email: req.body.email,
          password: req.body.password,
          passwordConfirm: req.body.passwordConfirm,
        });
        console.log(req.body);
      });
      res.status(201).json({
        status: `Success ?`,
        data: {
          user: newUser,
        },
      });
    };
      // app.js
const express = require('express');
const morgan = require('morgan');

const userRouter = require('./routes/userRoutes');
const app = express();
///////////////////////////////
// 1. Middlewares

if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}
app.use(express.json());
app.use(express.static(`${__dirname}/public`));
app.use((req, res, next) => {
  // console.log('Hello from the middleware');
  next();
});
app.use((req, res, next) => {
  req.requestTime = new Date().toISOString();
  next();
});
app.use('/api/v1/users', userRouter);
module.exports = app;

1 Ответ

0 голосов
/ 01 августа 2020

Ваш результат ничего не возвращает. Вы можете попробовать это:

 const db = require('./../database/db');
    const User = require('./../models/userModel');
    exports.signup = async function (req, res, next) {
      const newUser = await User.create({
          name: req.body.name,
          email: req.body.email,
          password: req.body.password,
          passwordConfirm: req.body.passwordConfirm,
        });
        console.log(req.body);
      res.status(201).json({
        status: `Success ?`,
        data: {
          user: newUser,
        },
      });
    };
...