繁体   English   中英

加载资源失败:服务器响应状态为 500(内部服务器错误),错误:请求失败,状态代码为 500

[英]Failed to load resource: the server responded with a status of 500 (Internal Server Error), Error: Request failed with status code 500

我正在开发这个社交媒体应用程序。 每次我尝试注册/登录应用程序时,它都会给我这个错误。

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Register.jsx:27 Error: Request failed with status code 500
    at createError (createError.js:16:1)
    at settle (settle.js:17:1)
    at XMLHttpRequest.onloadend (xhr.js:54:1)

这里是服务器端代码

const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");

//REGISTER
router.post("/register", async (req, res) => {
  try {
    //generate new password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

    //create new user
    const newUser = new User({
      username: req.body.username,
      email: req.body.email,
      password: hashedPassword,
    });

    //save user and respond
    const user = await newUser.save();
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json(err)
  }
});

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    !user && res.status(404).json("user not found");

    const validPassword = await bcrypt.compare(req.body.password, user.password)
    !validPassword && res.status(400).json("wrong password")

    res.status(200).json(user)
  } catch (err) {
    res.status(500).json(err)
  }
});

module.exports = router;

API中使用的Tech-Stack:MongoDB、Node.js、Express

当您提供 500 错误页面时,强烈建议在 output 中记录错误(不是在响应中,而是在日志中):

此外,发送响应时必须return ,以免多次写入头部。

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) { 
      return res.status(404).json("user not found");
    }
    const validPassword = await bcrypt.compare(req.body.password, user.password)

    if (!validPassword) {
      return res.status(400).json("wrong password")
    }

    res.status(200).json(user)
  } catch (err) {
    console.error(err)
    res.status(500).json(err)
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM