英文:
Registration response error in network tab
问题
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;
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');
const User = require('./models/user.model');
app.use(cors());
app.use(express.json());
mongoose.connect('mongodb+srv://ganeshnandhipati161999:Ganesh123%40%23%24@cluster1ganesh.n9trq4x.mongodb.net/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');
});
英文:
Hii I am trying to create a basic application with features of user registration and login
in that, I created node js + express server and connected mango db too here in the registration form user input details
like name email and password are displaying the server terminal
but
the network response showing error i am using cors also
my registration form code :`
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;
and server index.js code
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%24@cluster1ganesh.n9trq4x.mongodb.net/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
</details>
# 答案1
**得分**: 1
如果您看到此代码的捕获块:
```javascript
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' })
}
})
在这里,您的代码进入了捕获块,在捕获块中,您正在发送响应。在这个响应中,您发送了消息 "Duplicate email"。
我建议您在捕获块中通过检查错误来检查错误以及您收到了什么错误,修复这个问题将解决您的问题。
英文:
If you see your catch block of this code :
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' })
}
})
Here your code goes into the catch block, and in the catch block, you are sending the response. In this response, you have sent the message "Duplicate email"
I suggest you check in your catch block by checking the error, and what errors you are getting, fixing this will solve your issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论