Node.js 如何将表单数据从React前端发布到我的后端?
我试图弄清楚如何将React表单数据发送到后端和mongoDB数据库。我可以创建一个管理员,并在postman中测试时登录,但我不知道如何将表单数据从React发送到后端。我在后端使用Nodejs和Express 这是我的表格Node.js 如何将表单数据从React前端发布到我的后端?,node.js,reactjs,api,rest,express,Node.js,Reactjs,Api,Rest,Express,我试图弄清楚如何将React表单数据发送到后端和mongoDB数据库。我可以创建一个管理员,并在postman中测试时登录,但我不知道如何将表单数据从React发送到后端。我在后端使用Nodejs和Express 这是我的表格 import React, { useState } from 'react' import { Link } from 'react-router-dom' import dotenv from "dotenv"; dotenv.config();
import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import dotenv from "dotenv";
dotenv.config();
const baseUrl = process.env.REACT_APP_BASE_URL;
export const Register = () => {
const [admin, setAdmin] = useState({
username: '',
email: '',
password: ''
})
// define an admin
const { username, email, password } = admin
// use user input data to set the admin
const handleChange = (e) => {
e.preventDefault()
setAdmin({
...admin,
[e.target.name]: e.target.value
})
}
const registerAdmin = async (admin) => {
const res = await fetch(`${baseUrl}/admins/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(admin),
})
console.log(res)
}
// once admin is set, pass that data when submitted
const handleSubmit = (e) => {
e.preventDefault()
// call API function to send admin data to backend
registerAdmin(admin)
// after admin is sent to the backend, reset state
setAdmin({
username: '',
email: '',
password: ''
})
}
return (
<>
<form onSubmit={handleSubmit}>
<section className="hero is-primary is-fullheight">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-5-tablet is-4-desktop is-3-widescreen">
<form action="" className="box">
<h1 className="has-text-centered">Register Form</h1>
<div className="field">
<label htmlFor="" className="label">Username</label>
<div className="control has-icons-left">
<input type="text" value={username} name="username" onChange={handleChange} placeholder="username" className="input" required />
<span className="icon is-small is-left">
<i className="fa fa-envelope"></i>
</span>
</div>
</div>
<div className="field">
<label htmlFor="" className="label">Email</label>
<div className="control has-icons-left">
<input type="email" value={email} name="email" onChange={handleChange} placeholder="e.g. bobsmith@gmail.com" className="input" required />
<span className="icon is-small is-left">
<i className="fa fa-envelope"></i>
</span>
</div>
</div>
<div className="field">
<label htmlFor="" className="label">Password</label>
<div className="control has-icons-left">
<input type="password" value={password} name="password"
onChange={handleChange} placeholder="*******" className="input" required />
<span className="icon is-small is-left">
<i className="fa fa-lock"></i>
</span>
</div>
</div>
<div className="field">
<Link to='/' type="submit" className="button is-success">
Register
</Link>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</form>
</>
)
}
非常感谢我的代码中的任何提示或提示。
谢谢你抽出时间 您正在react中进行字符串化,因此需要在后端对其进行解析。您应该发布此部分的代码:
app.use('/admins',adminsRoutes)代码>所以我们可以看到它的去向:获取(
${baseUrl}/admins/register`
import express from 'express';
import session from 'express-session'
import connectMongo from 'connect-mongo';
import db from './db.js'
// allows us to take in incoming post request body
import bodyParser from 'body-parser'
import dotenv from 'dotenv';
// bring in the admins routes
import adminsRoutes from './routes/admins.js'
dotenv.config();
const app = express();
const PORT = process.env.PORT;
const MongoStore = connectMongo(session);
let sessionOptions = session({
secret: process.env.SECRET,
store: new MongoStore({client: db}),
resave: false,
saveUninitialized: false,
cookie: {maxAge: 1000 * 60 * 60 * 24, httpOnly: true}
})
app.use(sessionOptions)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// tell express to use the admins routes
// set the starting path for all the routes in the admins.js
app.use('/admins', adminsRoutes);
// route to the homepage
app.get('/', (req, res) => res.send('Hello from home page'));
app.listen(PORT, () => {
console.log(`Server is listening on port: ${PORT}`)
})