所以我用React做了一个Web应用程序。所以我创建了一个login/register函数,允许用户注册或登录到他们的帐户。我使用了一个express服务器发送http请求到MYSQL数据库,我还创建了两个端点到“/register”或“/login”。对于我的前端,我使用Axios将应用程序连接到这些端点,以将用户数据发布到数据库中。我的应用程序只工作时,服务器和客户端文件都运行在同一端口,这可能会中断当你刷新页面,然而,该应用程序将完全工作,如果你不刷新页面.所以我的问题是,我如何才能获得这些http请求,并将它们发布到我的数据库中,而没有我的前端和后端运行在同一端口.
前端:
import React, { useState } from "react";
import axios from 'axios';
function Login2() {
//Saving the values in the form variable
const [form, setForm] = useState({
username: '',
email: '',
password: '',
});
//mode determines whether the form should disply login or register
const [mode, setMode] = useState('login');
//message is used to disply any form of error to the user
const [message, setMessage] = useState('');
//it updates the users values in case a change has been made
//used a spread operator to update the form by targeting .name and .value
const handleChange = (e) => {
setForm({
...form,
[e.target.name]: e.target.value,
});
};
//it is used when the form is submitted, sends message to the backend to either login or register
//if successful/denied response is saved in message
const handleSubmit = (e) => {
e.preventDefault();
if (mode === 'login') {
axios.post('http://localhost:3000/login', form)
.then((response) => {
setMessage(response.data);
})
.catch((error) => {
setMessage(error.message);
});
} else {
axios.post('http://localhost:3000/register', form)
.then((response) => {
setMessage(response.data);
})
.catch((error) => {
setMessage(error.message);
});
}
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
placeholder="Username"
value={form.username}
onChange={handleChange}
/>
{mode === 'register' && (
<input
type="email"
name="email"
placeholder="Email"
value={form.email}
onChange={handleChange}
/>
)}
<input
type="password"
name="password"
placeholder="Password"
value={form.password}
onChange={handleChange}
/>
<button type="submit">
{mode === 'login' ? 'Login' : 'Register'}
</button>
<button type="button" onClick={() => setMode(mode === 'login' ? 'register' : 'login')}>
Switch to {mode === 'login' ? 'Register' : 'Login'}
</button>
</form>
{message && <p>{message}</p>}
</div>
);
};
export default Login2;
后端:
const express = require('express');
const app = express();
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: "??",
user: "??",
password: "??",
database: "??",
});
app.use(express.json());
app.post('/register', (req, res) => {
const { username, email, password } = req.body;
const reg = `INSERT INTO userTable (username, email, password) VALUES (?,?,?)`;
connection.query(reg, [username, email, password], (error) => {
if (error) throw error;
res.send('User registered successfully');
});
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
const log = `SELECT * FROM userTable WHERE username = ? AND password = ?`;
connection.query(log, [username, password], (error, results) => {
if (error) throw error;
if (!results.length) {
return res.send('Username or password is incorrect');
}
res.send('Login successful');
});
});
app.listen(4000, () => {
console.log('Server listening on port 4000');
});
1条答案
按热度按时间but5z9lq1#
你正在向一个错误的端口发出post请求。你的服务器运行在4000上,而你正在向端口3000发出axios post请求。在你的react代码中做如下修改:
以及
但是由于你是从一个不同的端口请求服务器,而不是它运行的端口(在你的项目中是4000),你会得到一个CORS错误。为此你需要安装
cors
包,并根据你的项目进行必要的配置。希望它能有所帮助。