cant get data from form to server - MERN

98
January 24, 2021, at 7:50 PM

im new and i cant get data from the form in server to insert it in the DB, heres the code:

form:

<form method = "post" action = "/register">
            <label>
                User Name:
                <input type = "text" name = "user" onChange = {(text) => setUser(text.target.value)}></input>
            </label>
            <label>
                Password:
                <input type = "password" name = "password"></input>
            </label>
            <input type = "submit" name = "Send" value = "Send"></input>
</form>

and the server.js:

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const PORT = 4000;
app.use(cors());
app.use(bodyParser.json());
mongoose.connect("mongodb://127.0.0.1:27017/Cook", {
    useNewUrlParser: true,
});
const connection = mongoose.connection;
app.post("/register", function(request, response) {
    let user = request.body.user;
    let password = request.body.password;
    console.log(user)
})

if anyone can help, would appreciate it :)

Answer 1

The issue is your are wrapping input field in label. I have updated the code below:

<form method="post" action="/register">
            <label>User Name:</label>
            <input type = "text" name = "user" value="keep any default if needed">
            <label> Password:</label>
            <input type = "password" name = "password">
            <input type="submit" value="Send" >
</form>
Answer 2

You need to explicitly enable this to parse form's data.


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
READ ALSO
How to store and deal with big chuncks of text between Javascript and HTML

How to store and deal with big chuncks of text between Javascript and HTML

So , I'm using HTML , css and JavaScript, I did a form , where the user will give different data, like name , adress , ID number , etc and I want to introduce those values into a preformatted text (like a renting contract)

60
Blinking Text If checkbox is checked to true

Blinking Text If checkbox is checked to true

I am trying to create when user check checkbox to yes(true) in Index Page Emergency column needs to flash text something like Emergency But unfortunately I try couple of methods but unsuccessfullyHere is so far what I did

66
how to make a mysql query and turn it into an array in php

how to make a mysql query and turn it into an array in php

if I have a query that looks like this in php

56