网络选项卡中的注册响应错误

huangapple go评论88阅读模式
英文:

Registration response error in network tab

问题

嗨,我正在尝试创建一个具有用户注册和登录功能的基本应用程序。

在这个应用程序中,我创建了一个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()); // 使用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');
});

为什么会显示这样的错误?我期望用户能成功注册并登录,并且详细信息将存储在MongoDB数据库中。

英文:

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 &quot;react&quot;;
function Register() {
const [name, setName] = useState(&#39;&#39;);
const [email, setEmail] = useState(&#39;&#39;);
const [password, setPassword] = useState(&#39;&#39;);
const [error, setError] = useState(&#39;&#39;);
async function Registeruser(event) {
event.preventDefault();
const response = await fetch(&#39;http://localhost:1337/api/register&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
},
body: JSON.stringify({
name,
email,
password
})
});
const data = await response.json();
if (response.ok) {
// Registration successful
console.log(&#39;Registration successful&#39;);
} else {
// Registration failed
setError(data.error || &#39;An error occurred&#39;);
}
}
return (
&lt;&gt;
&lt;div className=&quot;maindiv&quot;&gt;
&lt;h2&gt;Register&lt;/h2&gt;
&lt;p&gt;&lt;/p&gt;
&lt;form onSubmit={Registeruser}&gt;
&lt;input
value={name}
onChange={(e) =&gt; setName(e.target.value)}
placeholder=&quot;Your Name&quot;
/&gt;
&lt;p&gt;&lt;/p&gt;
&lt;input
value={email}
onChange={(e) =&gt; setEmail(e.target.value)}
placeholder=&quot;Email&quot;
/&gt;
&lt;p&gt;&lt;/p&gt;
&lt;input
value={password}
onChange={(e) =&gt; setPassword(e.target.value)}
placeholder=&quot;Password&quot;
/&gt;
&lt;br /&gt;
&lt;input type=&quot;submit&quot; value=&quot;Register&quot; /&gt;
&lt;/form&gt;
{error &amp;&amp; &lt;p className=&quot;error&quot;&gt;{error}&lt;/p&gt;}
&lt;/div&gt;
&lt;/&gt;
);
}
export default Register; 

and server index.js code

  const express = require(&#39;express&#39;);
const app = express();
const mongoose = require(&#39;mongoose&#39;);
const cors = require(&#39;cors&#39;);
const User = require(&#39;./models/user.model&#39;);
app.use(cors()); // Use the cors middleware
app.use(express.json());
mongoose.connect(&#39;mongodb+srv://ganeshnandhipati161999:Ganesh123%40%23%24@cluster1ganesh.n9trq4x.mongodb.net/test?retryWrites=true&amp;w=majority&#39;, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
app.post(&#39;/api/register&#39;, async (req, res) =&gt; {
console.log(req.body)
try {
await User.create({
name: req.body.name,
email: req.body.email,
password: newPassword,
})
res.json({ status: &#39;ok&#39; });
} catch (err) {
res.json({ status: &#39;error&#39;, error: &#39;Duplicate email&#39; })
}
})
app.post(&#39;/api/login&#39;, async (req, res) =&gt; {
const user = await User.findOne({
email: req.body.email,
password: req.body.password,
});
if (user) {
return res.json({ status: &#39;ok&#39;, user: true });
} else {
return res.json({ status: &#39;error&#39;, user: false });
}
});
app.listen(1337, () =&gt; {
console.log(&#39;Server started on 1337&#39;);
});   
```
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
如果你看到这段代码的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块中,你发送了响应。在这个响应中,你发送了消息"Duplicate email"。
我建议你在catch块中检查错误,并查看你得到了什么错误,修复这个问题将解决你的问题。
<details>
<summary>英文:</summary>
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 &quot;Duplicate email&quot;
I suggest you check in your catch block by checking the error, and what errors you are getting, fixing this will solve your issue.
</details>

huangapple
  • 本文由 发表于 2023年8月9日 16:00:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定