嗨,我正在尝试创建一个具有用户注册和登录功能的基本应用程序
在那里,我创建了node js + Express服务器,并在注册表单用户输入详细信息中也连接了mango db 服务器终端显示姓名、电子邮件和密码 但是
网络响应显示错误我也在使用 cors
我的注册表单代码:`
import { useState } from "react";
function Register() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
async function Registeruser(event) {
event.preventDefault();
const response = await fetch('http://localhost:1337/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
email,
password
})
});
const data = await response.json();
if (response.ok) {
// Registration successful
console.log('Registration successful');
} else {
// Registration failed
setError(data.error || 'An error occurred');
}
}
return (
<>
<div className="maindiv">
<h2>Register</h2>
<p></p>
<form onSubmit={Registeruser}>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your Name"
/>
<p></p>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<p></p>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<br />
<input type="submit" value="Register" />
</form>
{error && <p className="error">{error}</p>}
</div>
</>
);
}
export default Register;
和服务器index.js代码
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');
const User = require('./models/user.model');
app.use(cors()); // Use the cors middleware
app.use(express.json());
mongoose.connect('mongodb+srv://ganeshnandhipati161999:Ganesh123%40%23%[email protected]/test?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
app.post('/api/register', async (req, res) => {
console.log(req.body)
try {
await User.create({
name: req.body.name,
email: req.body.email,
password: newPassword,
})
res.json({ status: 'ok' });
} catch (err) {
res.json({ status: 'error', error: 'Duplicate email' })
}
})
app.post('/api/login', async (req, res) => {
const user = await User.findOne({
email: req.body.email,
password: req.body.password,
});
if (user) {
return res.json({ status: 'ok', user: true });
} else {
return res.json({ status: 'error', user: false });
}
});
app.listen(1337, () => {
console.log('Server started on 1337');
});
```
why it showing like these
I am expecting user registration and a successful registration and login and details will store in mongo db database
如果您看到此代码的 catch 块:
app.post('/api/register', async (req, res) => {
console.log(req.body)
try {
await User.create({
name: req.body.name,
email: req.body.email,
password: newPassword,
})
res.json({ status: 'ok' });
} catch (err) {
res.json({ status: 'error', error: 'Duplicate email' })
}
})
这里您的代码进入 catch 块,并在 catch 块中发送响应。在此回复中,您发送了消息“重复的电子邮件”
我建议您通过检查错误以及收到的错误来检查您的 catch 块,修复此问题将解决您的问题。