如何使用登录表单将数据从 React 发送到 Node 服务器?
How do I send data from React to Node server using login form?
我是 React JS、Node JS 和 Express 的新手。我用用户名和密码输入表单制作了一个简单的登录表单。在 SignIn.js 中,我将用户名和密码值发送到 index.js (节点),但我无法在 index.js.
中获取值
这是代码:
SignIn.js
import Axios from 'axios';
import {
DribbbleOutlined,
TwitterOutlined,
InstagramOutlined,
GithubOutlined,
} from "@ant-design/icons";
function onChange(checked) {
console.log(`switch to ${checked}`);
}
const { Title } = Typography;
const { Header, Footer, Content } = Layout;
export default class SignIn extends Component {
constructor(props) {
super(props)
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
name: '',
email: ''
}
}
onChangeUsername(e) {
this.setState({ username: e.target.value })
}
onChangePassword(e) {
this.setState({ password: e.target.value })
}
onSubmit(e) {
e.preventDefault()
}
render() {
const onFinish = (values) => {
const username = this.state.username;
const password = this.state.password;
Axios.post("http://localhost:3001/signin", {
username : username,
password : password,
}).then((Response)=> {
console.log(Response);
});
console.log("Success:", values);
};
const onFinishFailed = (errorInfo) => {
console.log("Failed:", errorInfo);
};
return (
<>
<Layout className="layout-default layout-signin">
<Header>
<div className="header-col header-brand">
<h5></h5>
</div>
<div className="header-col header-nav">
<h5>TITLE HERE</h5>
</div>
<div className="header-col header-btn">
</div>
</Header>
<Content className="signin">
<Row gutter={[24, 0]} justify="space-around">
<Col
xs={{ span: 24, offset: 0 }}
lg={{ span: 6, offset: 2 }}
md={{ span: 12 }}
>
<Title className="mb-15">Sign In</Title>
<Title className="font-regular text-muted" level={5}>
Enter your Username and password to sign in
</Title>
<Form
onFinish={onFinish}
onFinishFailed={onFinishFailed}
layout="vertical"
className="row-col"
>
<Form.Item
className="username"
label="Username"
name="username"
id="username"
rules={[
{
required: true,
message: "Please input your Username!",
},
]}
onChange={this.onChangeUsername}
>
<Input placeholder="Username" />
</Form.Item>
<Form.Item
className="username"
label="Password"
name="password"
id="password"
rules={[
{
required: true,
message: "Please input your password!",
},
]}
onChange={this.onChangePassword}
>
<Input placeholder="Password" />
</Form.Item>
{/*<Form.Item
name="remember"
className="aligin-center"
valuePropName="checked"
>
<Switch defaultChecked onChange={onChange} />
Remember me
</Form.Item>*/}
<Form.Item>
<Button
type="primary"
htmlType="submit"
style={{ width: "100%" }}
>
SIGN IN
</Button>
</Form.Item>
{/*<p className="font-semibold text-muted">
Don't have an account?{" "}
<Link to="/sign-up" className="text-dark font-bold">
Sign Up
</Link>
</p>*/}
</Form>
这是index.js(节点)
的代码
const { Result, message } = require('antd');
const express = require('express');
const app = express();
var cors = require('cors');
const mysql = require("mysql");
const db = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'wynadvm'
});
app.use(cors());
app.get('/', function (req, res) {
res.send('hello');
});
app.post('/signin', (req,res) => {
const username = req.query.username;
const password = req.query.password;
db.query(
"SELECT * from users where username = ? and password = ?",
[username , password],
(err,result) => {
if(err) {
res.send({err:err});
}
if(result.length > 0) {
res.send('result.response');
console.log(req.query.username);
//return res.redirect('/UserHomePage');
}
else
{
res.send('{message : "Wrong Username/Password Combination"}');
console.log(req.query.username);
//return res.redirect('/dashboard');
}
}
)
});
app.listen(3001,() => {
console.log("running on port 3001");
});
我的用户名和密码 const 在控制台日志中总是显示未定义。
您可以使用 axios
向后端发出 http 请求。
您可以从这里了解更多关于 axios 的信息:https://www.npmjs.com/package/axios
以下是如何使用 axios 提交登录请求的示例
axios.post('/signin', {
username: 'Fred',
password: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
您正在正文中发送数据,但您正在使用查询来获取用户名和密码,这就是您未定义的原因,请尝试使用
const username = req.body.username;
const password = req.body.password;
在前端:
将 import Axios from "axios"
编辑为 import axios from "axios"
,然后重写为:
axios.post("http://localhost:3001/signin", {
username : username,
password : password,
}).then((response)=> {
console.log(response);
}).catch(error => console.log(error))
在后端,如果你想从前端的正文请求中获取值
更容易,install body-parser。示例:
在终端中:
$ npm install body-parser
在您的后端代码中添加一些行:
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
然后将您从查询分配给正文的变量更改为:
发件人:
const username = req.query.username; //<--- you can't get value from query while you post data request in body
const password = req.query.password;
收件人:
const username = req.body.username;
const password = req.body.password;
我是 React JS、Node JS 和 Express 的新手。我用用户名和密码输入表单制作了一个简单的登录表单。在 SignIn.js 中,我将用户名和密码值发送到 index.js (节点),但我无法在 index.js.
中获取值这是代码:
SignIn.js
import Axios from 'axios';
import {
DribbbleOutlined,
TwitterOutlined,
InstagramOutlined,
GithubOutlined,
} from "@ant-design/icons";
function onChange(checked) {
console.log(`switch to ${checked}`);
}
const { Title } = Typography;
const { Header, Footer, Content } = Layout;
export default class SignIn extends Component {
constructor(props) {
super(props)
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
name: '',
email: ''
}
}
onChangeUsername(e) {
this.setState({ username: e.target.value })
}
onChangePassword(e) {
this.setState({ password: e.target.value })
}
onSubmit(e) {
e.preventDefault()
}
render() {
const onFinish = (values) => {
const username = this.state.username;
const password = this.state.password;
Axios.post("http://localhost:3001/signin", {
username : username,
password : password,
}).then((Response)=> {
console.log(Response);
});
console.log("Success:", values);
};
const onFinishFailed = (errorInfo) => {
console.log("Failed:", errorInfo);
};
return (
<>
<Layout className="layout-default layout-signin">
<Header>
<div className="header-col header-brand">
<h5></h5>
</div>
<div className="header-col header-nav">
<h5>TITLE HERE</h5>
</div>
<div className="header-col header-btn">
</div>
</Header>
<Content className="signin">
<Row gutter={[24, 0]} justify="space-around">
<Col
xs={{ span: 24, offset: 0 }}
lg={{ span: 6, offset: 2 }}
md={{ span: 12 }}
>
<Title className="mb-15">Sign In</Title>
<Title className="font-regular text-muted" level={5}>
Enter your Username and password to sign in
</Title>
<Form
onFinish={onFinish}
onFinishFailed={onFinishFailed}
layout="vertical"
className="row-col"
>
<Form.Item
className="username"
label="Username"
name="username"
id="username"
rules={[
{
required: true,
message: "Please input your Username!",
},
]}
onChange={this.onChangeUsername}
>
<Input placeholder="Username" />
</Form.Item>
<Form.Item
className="username"
label="Password"
name="password"
id="password"
rules={[
{
required: true,
message: "Please input your password!",
},
]}
onChange={this.onChangePassword}
>
<Input placeholder="Password" />
</Form.Item>
{/*<Form.Item
name="remember"
className="aligin-center"
valuePropName="checked"
>
<Switch defaultChecked onChange={onChange} />
Remember me
</Form.Item>*/}
<Form.Item>
<Button
type="primary"
htmlType="submit"
style={{ width: "100%" }}
>
SIGN IN
</Button>
</Form.Item>
{/*<p className="font-semibold text-muted">
Don't have an account?{" "}
<Link to="/sign-up" className="text-dark font-bold">
Sign Up
</Link>
</p>*/}
</Form>
这是index.js(节点)
的代码const { Result, message } = require('antd');
const express = require('express');
const app = express();
var cors = require('cors');
const mysql = require("mysql");
const db = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'wynadvm'
});
app.use(cors());
app.get('/', function (req, res) {
res.send('hello');
});
app.post('/signin', (req,res) => {
const username = req.query.username;
const password = req.query.password;
db.query(
"SELECT * from users where username = ? and password = ?",
[username , password],
(err,result) => {
if(err) {
res.send({err:err});
}
if(result.length > 0) {
res.send('result.response');
console.log(req.query.username);
//return res.redirect('/UserHomePage');
}
else
{
res.send('{message : "Wrong Username/Password Combination"}');
console.log(req.query.username);
//return res.redirect('/dashboard');
}
}
)
});
app.listen(3001,() => {
console.log("running on port 3001");
});
我的用户名和密码 const 在控制台日志中总是显示未定义。
您可以使用 axios
向后端发出 http 请求。
您可以从这里了解更多关于 axios 的信息:https://www.npmjs.com/package/axios
以下是如何使用 axios 提交登录请求的示例
axios.post('/signin', {
username: 'Fred',
password: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
您正在正文中发送数据,但您正在使用查询来获取用户名和密码,这就是您未定义的原因,请尝试使用
const username = req.body.username;
const password = req.body.password;
在前端:
将 import Axios from "axios"
编辑为 import axios from "axios"
,然后重写为:
axios.post("http://localhost:3001/signin", {
username : username,
password : password,
}).then((response)=> {
console.log(response);
}).catch(error => console.log(error))
在后端,如果你想从前端的正文请求中获取值 更容易,install body-parser。示例:
在终端中:
$ npm install body-parser
在您的后端代码中添加一些行:
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
然后将您从查询分配给正文的变量更改为:
发件人:
const username = req.query.username; //<--- you can't get value from query while you post data request in body
const password = req.query.password;
收件人:
const username = req.body.username;
const password = req.body.password;