0

POST requests return null. The req.body..... values are undefined. I tried to verify it arrives to the server in JSON format, but i am not sure I am doing it in a right way.... :-( Thanx a lot for help, amigos!

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require("cors");

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');

var app = express();  
app.set('view engine', 'ejs')
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const { MongoClient } = require("mongodb");
const uri = "mongod...the string is ok....y";
const client = new MongoClient(uri);
const database = client.db('holdocsDB');
const records = database.collection('records');

app.post("/users", async (req, res) => {
    console.log('hola pooost');
    console.log("req.body.age: " + req.body.age);

    try {
        // create a document to insert
        const newRecord = {
            firstName: req.body.firstName,
            age: req.body.age

        }
        const result = await records.insertOne(newRecord);
        console.log(`A document was inserted with the _id: ${result.insertedId}`);
        // } finally {
        //   await client.close();
        // }
    } catch {
        (e) => (console.error(e));
    }
});

// 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.json('error');
});

module.exports = app;

When I hardcode some values to be posted in express POST route (instead of extracting the values from req.body) - it works well.

    function RecordSearchBar() {

        const [form, setForm] = useState({
            firstName: "",
            age: 0
        });

        // const navigate = useNavigate();

        function updateForm(value) {
            return setForm((prev) => {
                return { ...prev, ...value };
            });
        }

        async function onSubmit(e) {
            e.preventDefault();
            const newPerson = { ...form };
            
            await fetch("http://localhost:3001/users/add", {
                method: "POST",
                headers: {
                "Content-Type": "application/json",
                },
                body: JSON.stringify(newPerson),
            })
            .catch(error => {
                window.alert(error);
                return;
            });
            
            setForm({ firstName: "", age: ""});
            // navigate("/users");
        }   

        return (
            <>
                <h2>Search records:</h2>  
                <form onSubmit={onSubmit} id='search-form'>
                    <div className="form-group">
                        <label htmlFor="firstName">First name</label>
                        <input
                        type="text"
                        className="form-control"
                        id="name"
                        value={form.name}
                        onChange={(e) => updateForm({ name: e.target.value })}
                        />
                    </div>
                    <div className="form-group">
                        <label htmlFor="age">Age</label>
                        <input
                        type="number"
                        className="form-control"
                        id="position"
                        value={form.position}
                        onChange={(e) => updateForm({ position: e.target.value })}
                        />
                    </div>
                    <div className="form-group">
                        <input
                        type="submit"
                        value="Add record"
                        className="btn btn-primary"
                        />
                    </div>
                </form>
        
            </>
Toto
  • 13
  • 3
  • 1) Try `console.log(req.body)`. 2. Share the client-side code. – Evert Jan 17 '23 at 17:14
  • Thanx for response! 1) console.log(req.body) returns req.body: [object Object]; 2) actually I have the same problem no matter if I do a POST request from client of via POSTMAN – Toto Jan 17 '23 at 17:22
  • If you're seeing `[object Object]`, it means the client didn't convert the parameters to JSON, it tried to send the object without converting it. That's what you get if you convert an object to a string. See https://stackoverflow.com/questions/4750225/what-does-object-object-mean – Barmar Jan 17 '23 at 17:23
  • `RecordSearchBar()` function is really messed up. By the way, functions declared with Uppercase is treated as `class`. That's one of the methods of creating a class in JS. – jkalandarov Jan 17 '23 at 18:27
  • hi @jkalandarov, it is a standard react component function, as far as I understand. the Uppercase name is what is expected for react component – Toto Jan 17 '23 at 18:37
  • Your `app.post("/users"` handler doesn't use `res`. It doesn't serve a response at all. Your code doesn't do `res.send` or `res.status` or anything typical. – Wyck Jan 17 '23 at 19:52

1 Answers1

0

Solved! I had to correct the type conversion of request body using JSON.parse() and JSON.stringify():

app.post("/users", async (req, res) => {
  console.log("req.body: " + JSON.stringify(req.body));

  let newRecordStringified = JSON.stringify(req.body)
  try {
    // create a document to insert
    const newRecord = {
      firstName: req.body.firstName,
      age: req.body.age
      // firstName: "Mamile",
      // age: 33
    }
    const result = await             records.insertOne(JSON.parse(newRecordStringified));
    console.log(`A document was inserted with the _id: ${result.insertedId}`);
  // } finally {
  //   await client.close();
  // }
   } catch {
     (e) => (console.error(e));
   }
})
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Toto
  • 13
  • 3