简体   繁体   中英

NodeJS req.body empty in funtion nodejs - Rest API whit ExpressJs and sequelize

I'm using ExpressJS and sequelize. I need invoke two functions ("accoun.js" and "people.js") into a main function (fullaccount.js) receving data in "fullaccount.js" for submit and process in the others functions, I received ready req.body in "fullaccount.js" but in "accoun.js" and "people.js" REQ.BODY IS EMPTY

app.js

const express = require('express');
const morgan = require('morgan');

var app= express(); 
app.set('port',process.env.PORT || 4094); 
app.use(morgan('dev')); 
app.use(express.urlencoded({extended:false})); 
app.use(express.json());        
app.use(require('./routes/back/account.route'));
app.use(require('./routes/back/people.route'));
app.listen(app.get('port'), function(){
  console.log('Working in port: '+app.get('port'));
});

fullaccount.js

const account=require( './account.ctrl');
const people= require ('./people.ctrl');
import Sequelize from 'sequelize';

export function add(req, res) {
  console.log(req.body); //-> it's ready. RETURNING JSON
  const {nick,pass,email,firstNam,lastName,identCard,birthDate,genderId,countryId}=req.body;

  account.add({nick,pass,email},res); //=>> invoke add method from account controller return undefined
  people.add({firstName,lastName,identCard,birthDate,genderId,countryId},res); //=>> invoke add method from people controller return undefined
}

account.js

import Account from '../../db/models/account.mdl';

export function add(req, res) {
  console.log(req.body); // it's return undefined 
};

people.js

import People from '../../db/models/people.mdl'; 

export function add(req, res) {
  console.log(req.body); // it's return undefined  
};

I don't know what the error is, I need help

req.body is undefined because you are not passing the initial request to account.add or people.add

For example, for account, you are actually passing an object that contains nick , pass and email

account.add({nick, pass, email}, res); // req.nick, req.pass, req.email are available

To avoid confusion, you should rename the req parameter in account.add to data . Good names will save you a lot of headaches. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM