Home > other >  Cant get the request content from a form with nodejs, express and mongoDB
Cant get the request content from a form with nodejs, express and mongoDB

Time:08-05

I need to access the data posted by a form to handle it with node and express, so then I can add it to mongoDB. The answer I get for NAME is "undefined" and for DATA "[object Object]". In mongoDB the _id is created but all values are null. How can I access the user input like their username?

index form:
<form action="/projectData" method="POST" >
    <label for="name"><b>Name</b></label>
    <input type="text" placeholder="Project name" name="project_name" required>
    // More inputs like description, site and code, same as shown above [...] 
    <button type="submit" >Add</button>
</form>


server:
var express = require("express");
var app = express();
app.use(express.json()); // I dont really know how this line works

var mongoPath = "mongodb://localhost";
var mongoClient = require('mongodb').MongoClient;

app.set("views", __dirname   '/views');

app.get("/", function (request, response){
    response.sendFile(__dirname   "/views/index.html");
});

app.post("/projectData", function(request, response){

    var something = request.body.project_name;
    console.log("NAME: "   something); // undefined

    var data = {
        name : request.body.project_name,
        description : request.body.project_description,
        view : request.body.project_site,
        code : request.body.project_code
    }
    console.log("DATA: "   data); // [object Object]


    mongoClient.connect(mongoPath, function(error, client){

        var db = client.db('myDB');

        var result = {};
        if (error) {
            result.message = "Error on connection to database";
            response.send(result);
        }
        else {
            var collection = db.collection("projects");
            collection.insertOne(data, function(error, collection){
                if (error) throw error;
                console.log("Record inserted Successfully"); // it shows this message after the 2 console logs
            });
        }
    });
});

CodePudding user response:

You need to install body-parser npm package to parse form data.

npm i body-parser

then these lines in server file

const bodyParser = require("body-parser");

app.use(
    bodyParser.urlencoded({
        extended: true,
    })
);
  • Related