Node.JS and Express Insert with problem

Asked

Viewed 410 times

2

I am new as Node.JS Express programmer with Mysql, I created the implementation to save, but he create the registry with null in the table, see how I performed the test in Postman;

inserir a descrição da imagem aqui

This is my entity;

module.exports = (sequelize, Sequelize) => {
    const Customer = sequelize.define('customer', {
      firstname: {
        type: Sequelize.STRING
      },
      lastname: {
        type: Sequelize.STRING
      },
      age: {
          type: Sequelize.INTEGER
      }
    });
    
    return Customer;
}

This is the method responsible for saving;

const db = require('../config/db.config.js');
const Customer = db.customers;

// Post a Customer
exports.create = (req, res) => {    
    // Save to MySQL database
    Customer.create({  
      firstname: req.body.firstname,
      lastname: req.body.lastname,
      age: req.body.age
    }).then(customer => {       
        // Send created customer to client
        res.send(customer);
    });
};
 

What could be wrong?

UPDATING ================================

Route archive;

module.exports = function(app) {
 
    const customers = require('../controller/customer.controller.js');
 
    // Create a new Customer
    app.post('/api/customers', customers.create);
 
    // Retrieve all Customer
    app.get('/api/customers', customers.findAll);
 
    // Retrieve a single Customer by Id
    app.get('/api/customers/:customerId', customers.findById);
 
    // Update a Customer with Id
    app.put('/api/customers/:customerId', customers.update);
 
    // Delete a Customer with Id
    app.delete('/api/customers/:customerId', customers.delete);
}

=======================================================

Caused this error;

C:\SQL\api1>node server.js
internal/modules/cjs/loader.js:583
    throw err;
    ^

Error: Cannot find module '../controllers/customer.controller'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (C:\SQL\api1\app\route\customer.route.js:2:18)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (C:\SQL\api1\server.js:5:20)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:236:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)

=======================================

Another error message;

node server.js
C:\SQL\api1\server.js:15
app.use('/api/customers', routes);
                          ^

ReferenceError: routes is not defined
    at Object.<anonymous> (C:\SQL\api1\server.js:15:27)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:236:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)
  • Sorry, where do you think there should be clasps?

  • What it means is that you should try to remove "[" and "]", which denote an array of objects, and send only the content between "{" and "}", which is the object itself.

  • Please, what part of my code should I remove the "[" and "]" ?

  • No Postman, not your code.

  • The same thing happens if I change from body to raw, I would like to know from @Statelessdev what I could change in Postman to save the records?

  • how it would change?

  • just put, check my post update please.

  • i believe that the console.log command only works in the browser, even though I tried it and it did not appear anything, neither in the browser nor in the msdos console

  • @Sorack unfortunately his answer didn’t help, and I’m still trying to solve my problem, it generated some errors in the development IDE itself.

Show 4 more comments

1 answer

2


The first problem occurs that the type of body that you are using on Postman is incorrect. Use the x-www-form-urlencoded:

Postman


Checking the code you have made available in your repository, I suggest the following changes:

In the server.js:

const express    = require('express');
const app        = express();
const bodyParser = require('body-parser');
const db         = require('./app/config/db.config.js');
const customer   = require('./app/route/customer.route');

// force: true will drop the table if it already exists
db.sequelize.sync({force: true}).then(() => {
  console.log('Drop and Resync with { force: true }');
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Registra a rota /api/customer para as rotas descritas em ./app/route/customer.route.js
app.use('/api/customers', customer);

// Create a Server
var server = app.listen(3000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("App listening at http://%s:%s", host, port)
});

The route file will look like this (app/route/customer.route.js):

const customer = require('../controller/customer.controller');
const express  = require('express');

const router = express.Router();

router.post('/', customer.create);

module.exports = router;

In turn the controller (app/controller/customer.controller.js):

const db = require('../config/db.config.js');
const Customer = db.customers;

async function create(req, res) {
  try {
    req.send(await _save(req.body));
  } catch(e) {
    res.status(500).send(e);
  }
}

async function _save(customer) {
  return Customer.create({  
    firstname: customer.firstname,
    lastname:  customer.lastname,
    age:       customer.age
  });
}

module.exports = {
  create
}
  • I put the method in the controller, the route class can not see the saved method as with the other method that exist in the controller class, I will make available my repository https://github.com/wladyband/node_com_mysql I would like to thank you for trying to help me.

  • Could you please take a look at my post, I just updated, when I had it compiled it generated an error. Maybe we wouldn’t have to waste too much time on this project of mine, I didn’t develop it, and I found it on the Internet. All I need is a Node Express project with Mysql that is a working CRUD, but that uses the Models implementation. I know how to create a CRUD project with mysql, but it doesn’t use models, and I was told that using models is a practical.

  • I tried to analyze the change you made in the file customer.route.js but not being able to see.

  • You can click the indicator below the answer "edited ?? mins ago" to see the change

  • i updated the post, gave another error message.

  • 1

    thank you very much for the help, I managed to succeed, thank you very much for the patience. thank you very much.

  • @wladyband we are there for this

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.