Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

node.js - cant get data from form to server - MERN

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 :)

question from:https://stackoverflow.com/questions/65858521/cant-get-data-from-form-to-server-mern

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...