Home > front end >  POST request returns null values (node.js)
POST request returns null values (node.js)

Time:01-18

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>
        
            </>

CodePudding user response:

How did you test it? because when doing console.log on newRecord it returns the values

CodePudding user response:

solved! I had to correct the type conversion of request body usin 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));
              }
    }
    )

  • Related