如何解决我在 react 中使用 axios post 时遇到问题
当我使用 axios 时,帖子错误很严重。我也安装了cors。我不知道为什么会发生这种情况。这是我的反应代码。
import React,{ useState } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
export default function Login() {
const [Email,SetEmail] = useState('')
const [Password,SetPassword] = useState('')
return (
<div>
<h1>Login</h1>
<input type="text" placeholder="Email" value={Email} onChange={(e) => SetEmail(e.target.value)} />
<input type="password" placeholder="Password" value={Password} onChange={(e) => SetPassword(e.target.value)} />
<button type="submit" onClick={(e) => {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const body = JSON.stringify({ Email,Password })
axios.post('http://localhost:4000/app/signin',body,config)
.then((response) => console.log(response.data))
}}>Login</button>
<div style={{ float: "right",marginTop: "10px" }}>
<Link to="/signup" style={{ color: "white" }}>
SIGN UP
</Link>
</div>
</div>
)
}
我正在练习登录。我没有使用表单标签。因为当我向后端提交数据时,控制台初始化并且看不到发生了什么。接下来是我的 node.js 代码。
router.post(
'/signin',[
check('email','Type proper e-mail').isEmail(),check('password','Password is required').not().isEmpty()
],async (request,response) => {
try{
const {email,password} = request.body;
let user = await signUpTemplatecopy.findOne({email});
const errors = validationResult(request);
if (!errors.isEmpty()) {
return response.status(401).json({errors: errors.array()});
}
if (!user){
return response.status(401).json({ msg: "There is no user with this e-mail"});
}
let isPasswordMatch = await bcryptjs.compare(password,user.password);
if (isPasswordMatch) {
const payload = {
user: {
id : user.id
}
}
jwt.sign(
payload,config.get('jwtSecret'),(err,token) => {
if (err) throw err;
response.json({token});
}
)
} else return response.status(401).json({msg: "wrong password"});
} catch (error) {
console.log(error.msg);
return response.status(500).json({msg: "Server Error..."});
}
})
我什至无法猜测问题是什么。请帮我解决这个问题。
解决方法
为了验证电子邮件和密码,我建议使用 express-validator
库。你会像这样实现它:
router.post(
"/signin",[
body("email").isEmail().withMessage("Email must be valid"),body("password")
.trim()
.notEmpty()
.withMessage("You must supply a password"),]
您可能需要一个错误处理中间件。 signupTemplateCopy
对于您的 User
模型来说似乎是一个令人困惑的命名约定,但您可以取而代之,并像这样对其运行 if 条件:
async (req,res) => {
const { email,password } = req.body;
const existingUser = await User.findOne({ email });
if (!existingUser) {
throw new BadRequestError("Invalid Credentials");
}
对于您在上面看到的名为 BadRequestError()
的 @dc_microurb/common@^1.0.7
,我使用了一个鲜为人知的 npm 库。此外,除了 bcrypt
,您可能还想尝试使用 scrypt
库中的 crypto
,但您所拥有的会起作用。
我也不确定您是如何生成 JWT 的。假设您按照我的建议进行操作,const existingUser = await User.findOne({ email });
或在您的情况下为 const existingUser = await signUpTemplateCopy.findOne({ email });
,那么您将使用 existingUser
或在您的情况下 user
来生成 JWT像这样:
const userJwt = jwt.sign(
{
id: existingUser.id,email: existingUser.email,},process.env.JWT_KEY!
);
然后您需要将该 JWT 存储在我在您的代码中没有看到的会话对象中,如下所示:
req.session = {
jwt: userJwt,};
然后你终于可以发回 res.status(200).send(user);
或者在我的例子中,res.status(200).send(existingUser);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。