我有一个表单,应该将用户输入发送到我的 mongodb 集群:
// Registration.jsx
import React, { useState } from 'react';
import axios from 'axios';
const Registration = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [successMessage, setSuccessMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
// Validation logic (you can use a library like Yup for form validation)
if (!email || !password) {
setError('Email and password are required.');
return;
}
console.log("Test");
// Registration API call
const response = await axios.post('/api/auth/register', { email, password });
console.log(response);
setSuccessMessage(response.data.message);
} catch (error) {
setError(error.response.data.message);
}
}
return (
<div className="container">
<div className="row">
<div className="col-md-6 offset-md-3">
<h2>Registration</h2>
{error && <div className="alert alert-danger">{error}</div>}
{successMessage && <div className="alert alert-success">{successMessage}</div>}
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="email" className="form-label">Email address</label>
<input type="email" className="form-control" id="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
</div>
<div className="mb-3">
<label htmlFor="password" className="form-label">Password</label>
<input type="password" className="form-control" id="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
</div>
<button type="submit" className="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
);
}
export default Registration;
提交请求时,请求将启动,然后在一段时间后崩溃并出现 408 错误代码,我已经在实际的前端和邮递员上进行了测试,并得到了相同的结果。我不确定为什么请求超时。非常感谢任何帮助,包括我认为以下相关的任何代码:
//auth.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user.js');
const registerValidation = require('../middleware/validation.js');
const { validationResult } = require('express-validator');
console.log("This is before all routes");
//Register Route
router.post('/register', registerValidation, async (req, res) => {
// Validate request body
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
console.log("This log is just before the try catch for creating the new user.");
try {
// Check if user already exists
let user = await User.findOne({ email });
if (user) {
return res.status(400).json({ msg: 'User already exists' });
}
// Create new user
user = new User({
email,
password
});
console.log(user);
// Hash password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
// Save user to database
await user.save();
console.log("This console log is right after the user gets saved to the database")
// Generate JWT token
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: '1d' },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
res.status(200).json({ message: 'Registration successful', email });
console.log("200 msg sent");
});
//Email Verification Route
router.get('/verify/:token', async (req, res) => {
const token = req.params.token;
try {
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Update user's verified status
await User.findByIdAndUpdate(decoded.user.id, { verified: true });
res.json({ msg: 'Email verified successfully' });
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
// Login Route
router.post('/login', async (req, res) => {
const { email, password } = req.body;
try {
// Check if user exists
let user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: 'Invalid Credentials' });
}
// Check if password matches
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ msg: 'Invalid Credentials' });
}
// Check if user is verified
if (!user.verified) {
return res.status(400).json({ msg: 'Please verify your email' });
}
// Generate JWT token
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: '1d' },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
// Forgot password route
router.post('/forgot-password', async (req, res) => {
const { email } = req.body;
try {
// Check if user exists
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: 'User not found' });
}
// Generate verification code
const verificationCode = Math.floor(100000 + Math.random() * 900000);
// Implement logic to send verification code to user's email using SendGrid
res.json({ msg: 'Verification code sent to your email' });
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
// Verify Code route
router.post('/verify-code', async (req, res) => {
const { email, verificationCode } = req.body;
try {
// Check if user exists
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: 'User not found' });
}
// Check if verification code matches
if (user.verificationCode !== verificationCode) {
return res.status(400).json({ msg: 'Invalid verification code' });
}
// If verification code matches, update user's verified status
user.verified = true;
// Clear verification code after successful verification
user.verificationCode = null;
await user.save();
res.json({ msg: 'Verification code verified' });
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
//Rest Password route
router.post('/reset-password', async (req, res) => {
const { email, newPassword } = req.body;
try {
// Check if user exists
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: 'User not found' });
}
// Hash new password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(newPassword, salt);
// Save new password to database
await user.save();
res.json({ msg: 'Password reset successful' });
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
module.exports = router;
//user.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
accountType: { type: String, enum: ['Admin', 'Paid', 'Free'], default: 'Free' },
verified: { type: Boolean, default: false }
});
const User = mongoose.model('User', userSchema);
module.exports = User;
const express = require('express');
const connectDB = require('./config/db.js');
const cors = require('cors');
const proxyMiddleware = require('./middleware/Proxy.js');
const app = express();
// Connect to MongoDB
connectDB();
// Middleware
app.use(cors()); // Enable CORS for all routes
app.use(express.json()); // Parse JSON bodies
proxyMiddleware(app); // Apply proxy middleware
// Routes
app.use('/api/auth', require('./routes/auth.js'));
// Define port
const PORT = process.env.PORT || 5000;
app.get('/', (req, res) => {
res.send('Hello, welcome to the API server!');
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
// backend/config/db.js
const mongoose = require('mongoose');
require('dotenv').config({ path: '' });
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB Connected');
} catch (error) {
console.error('Error connecting to MongoDB:', error.message);
process.exit(1); // Exit process with failure
}
};
module.exports = connectDB;
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Percy",
"license": "ISC",
"dependencies": {
"@sendgrid/mail": "^8.1.3",
"axios": "^1.6.8",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-validator": "^7.0.1",
"http-proxy-middleware": "^3.0.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.3.1",
"nodemailer": "^6.9.13",
"nodemon": "^3.1.0",
"sendgrid": "^5.2.3"
}
}
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.8",
"bootstrap": "^5.3.3",
"react": "^18.2.0",
"react-bootstrap": "^2.10.2",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
这里还有请求和响应标头的原始数据:
HTTP/1.1 408 Request Timeout
x-powered-by: Express
access-control-allow-origin: *
connection: close
date: Mon, 22 Apr 2024 20:18:29 GMT
content-length: 0
POST /api/auth/register HTTP/1.1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 58
Content-Type: application/json
Host: localhost:3000
Origin: http://localhost:3000
Referer: http://localhost:3000/register
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36
sec-ch-ua: "Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
如果您可以共享您的 registerValidation 代码,因为您将其添加为中间件,如果不调用 next ,它可能会挂在那里