Home > database >  req.body is showing me object in reverse order in node and express backend app
req.body is showing me object in reverse order in node and express backend app

Time:12-04

I was building a To-do list web app using mern stack with redux. I created a simple form to enter the data but while sending post data to the backend I'm facing difficulty. My form textfield area name is 'task' (E.g. ) and I'm passing let's say 'jonas' as the value. Everythin on the front-end is working fine but in the backend when I console the req.body in post method callback function, I do get {jonas: ' '} as the value. Why is this happening? I mean it should have been {task: 'jonas'}, right?

Please someone help me with this thing. I'm stuck on this problem for last two days. I could have shared the code screenshots but the codebase is really huge.

I should get output as {task: 'jonas'} (This is always the correct format for any textfield input data.) But all I'm getting is {jonas: ''}.

Front-end (React with Material-UI):

import React, { Fragment, useState } from 'react';
import { useDispatch } from 'react-redux';
import { createTasks } from './../../Actions/TaskActions';
import { Container, FormControl, Button } from '@mui/material';

const Form = props => {
  const [task, setTask] = useState();
  const dispatch = useDispatch();

  const submitHandler = event => {
    event.preventDefault();
    console.log(task);
    dispatch(createTasks(task));
    setTask('');
  };

  return (
    <Fragment>
      <Container maxWidth="sm">
        <form onSubmit={submitHandler} method="post">
          <FormControl fullWidth={true}>
            <input
              name="task"
              type="text"
              value={task}
              onChange={event => setTask(event.target.value)}
            />
            <Button variant="contained" style={{ marginTop: 5 }} type="submit">
              Add tasks
            </Button>
          </FormControl>
        </form>
      </Container>
    </Fragment>
  );
};

export default Form;

React-Redux (Dispatch Action)

import * as api from './../API/API';

export const createTasks = task => async dispatch => {
  try {
    console.log(task);
    const response = await api.addTasks(task);
    console.log(response);

    dispatch({ type: 'CREATE', payload: response });
  } catch (err) {
    console.log(err);
  }
};

API (Connection of front-end with backend)

import axios from 'axios';

const url = 'http://localhost:5000/tasks';

export const addTasks = newTask => axios.post(url, newTask);

app.js (backend)

const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const bodyParser = require('body-parser');

const taskRouter = require('./Routes/taskRouter');

const app = express();

app.use(cors());
app.use(bodyParser.json({ limit: '10000kb', extended: true }));
app.use(bodyParser.urlencoded({ limit: '10000kb', extended: true }));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));

// app.get('/', (req, res) => {
//   res.status(200).send('Hello world!');
// });

app.use('/tasks', taskRouter);

module.exports = app;

server.js(backend)

const dotenv = require('dotenv');
const mongoose = require('mongoose');

dotenv.config({ path: `${__dirname}/config.env` });
const app = require('./app');

const DB = process.env.DATABASE.replace(
  '<password>',
  process.env.DATABASE_PASSWORD
);

mongoose
  .connect(DB, {
    useNewUrlParser: true,
  })
  .then(() => console.log('Connected to database...'))
  .catch(err => console.log(err));

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server is running on the port ${port}...`);
});

router(backend)

const express = require('express');
const taskController = require('./../Controllers/taskController');

const taskRouter = express.Router();

taskRouter
  .route('/')
  .get(taskController.getTasks)
  .post(taskController.createTask);

taskRouter
  .route('/:id')
  .patch(taskController.updateTask)
  .delete(taskController.deleteTask);

module.exports = taskRouter;

controller(backend)

const taskModel = require('./../Model/taskModel');

exports.createTask = async (req, res) => {
  try {
    // const response = req.body.name;
    // console.log(response);
    console.log(req.body);
    const bodyData = req.body;
    // const response = Object.keys(req.body)[0];
    // console.log(typeof response);

    const answer = new taskModel({
      ...bodyData,
      date: new Date().toISOString(),
    });

    console.log(answer);

    await answer.save();

    res.status(200).json(answer);
  } catch (err) {
    res.status(400).send(err);
  }
};

model(backend)

const mongoose = require('mongoose');

const taskSchema = mongoose.Schema({
  task: {
    type: String,
    required: [true, 'A to-do list must have a task name'],
  },
  date: {
    type: Date,
    default: new Date(),
  },
});

const taskModel = mongoose.model('taskModel', taskSchema);

module.exports = taskModel;

CodePudding user response:

So the thing, the "task", you pass along from the form to the dispatcher to the axios request is just a string, "jonas", correct? Somewhere down the line you need to turn it into an object,

const newTask = {
    task: theTaskVariable     // "jonas" in this case
}

If you say that the front end works as is, you could make the change in the API connection before making the axios request. I would probably make the change in the form submitHandler already and then make changes to the front end accordingly as well.

  • Related