【问题标题】:Uncaught (in promise) Error: Request failed with status code 400 at createError (createError.js:16) at settle at XMLHttpRequest.onloadend未捕获(承诺中)错误:在 XMLHttpRequest.onloadend 解决时,在 createError (createError.js:16) 处请求失败,状态码为 400
【发布时间】:2021-11-26 09:59:33
【问题描述】:

当我从 axios 获取数据时出现上述错误,当所有验证都正确时,我得到了数据,但是当我尝试发送错误数据时,它给了我上述错误

import React from 'react'
import { TextField, Button } from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import GoogleIcon from '@mui/icons-material/Google';
import FacebookIcon from '@mui/icons-material/Facebook';
import { Link } from "react-router-dom";
import "../styles/home.css"
import useInputState from "../hooks/useInputState"
import axios from 'axios';

function Login() {

    const [username, updateUsername, resetUsername] = useInputState("")
    const [password, updatePassword, resetPassword] = useInputState("")
    const HOST = "http://localhost:8080"

    const handleSubmit = async (evt) => {
        evt.preventDefault()
        const config = { headers: { 'Content-Type': 'application/json' } }
        const data = JSON.stringify({ username, password })
        console.log(data)
        const response = await axios.post(`${HOST}/api/auth/login`, data, config)
        console.log(response.data)
        resetUsername()
        resetPassword()
        // if (resp.data.success) {
        //     console.log("redirecting to oppp")
        // } else {
        //     alert("invalid credentials")
        // }
    }

    return (
        <div>
            <div className="container mt-5 addnotes" >
                <Button className="mb-4" variant="text" color="secondary" startIcon={<ArrowBackIcon />} component={Link} to="/" style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif" }}>Home</Button>
                <h2 style={{ fontWeight: "Bold" }}>Login</h2>
                <p className="mb-4">Sign in on the internal platform</p>
                <div className="d-flex">
                    <Button size="large" fullWidth className="mb-4 me-4" variant="contained" color="primary" startIcon={<FacebookIcon />} component={Link} to="/" style={{ textTransform: "none", fontSize: "1.1rem", color: "White", fontFamily: "'Poppins', sans-serif" }}>Login with Facebook</Button>
                    <Button size="large" fullWidth className="mb-4" variant="contained" color="error" startIcon={<GoogleIcon />} component={Link} to="/" style={{ textTransform: "none", fontSize: "1.1rem", color: "White", fontFamily: "'Poppins', sans-serif" }}>Login with Google</Button>
                </div>
                <p className="mb-4 d-flex justify-content-center">or login with username and password</p>
                <form onSubmit={handleSubmit}>
                    <div className="mb-4">
                        <TextField value={username} onChange={updateUsername} inputProps={{ minLength: 1 }} color="secondary" label="Username" variant="outlined" fullWidth required style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }} />
                    </div>
                    <div className="mb-4">
                        <TextField type="password" value={password} onChange={updatePassword} inputProps={{ minLength: 1 }} color="secondary" label="Password" variant="outlined" fullWidth required style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }} />
                    </div>
                    <Button disabled={username.length < 1 || password.length < 1} type="submit" fullWidth size="large" className="mb-4" variant="contained" color="secondary" style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }}>Add Note</Button>
                </form>
                <p>Don't have an account? <Link to="/register" >register</Link> </p>
            </div>
        </div>
    )
}

export default Login

当我尝试提供错误输入时,handlesubmit 函数中发生错误,这应该给我一个错误的响应,但它给了我以下错误,并且 usernamereset 和 passwordReset 没有被执行,但是当我提供正确的用户名和密码时我得到了正确的数据

错误:

Uncaught (in promise) Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.onloadend (xhr.js:66)

该路由的后端代码:

router.post('/login', validateUserLogin, catchAsync(loginUser))
module.exports.loginUser = async (req, res) => {
    const { username, password } = req.body
    const foundUser = await User.findAndValidate(username, password)
    if (foundUser) {
        const data = {
            user: { id: foundUser._id }
        }
        const authToken = jwt.sign(data, process.env.JWT_KEY)
        res.send({ success: true, authToken })
    } else {
        return res.status(400).json({ success: false, err: { user: foundUser }, message: "invalid credentials !!" })
    }
}

当我发送错误的用户名密码时,我没有收到此无效凭据消息

【问题讨论】:

  • 这似乎是后端和代码中的错误。预期的行为是什么。另外,我建议您在 axios 调用中使用 then catch。
  • 我还编辑并上传了后端代码
  • createError 的第 16 行和结算文件的第 17 行是什么?
  • 我不知道兄弟
  • 那么错误可能在 findAndValidate 方法或 jwt.sign 中

标签: node.js reactjs axios mern


【解决方案1】:

TL:DR:你做的一切都是对的

我想在后端,有一个处理程序会检查您的请求是否正确,如果不正确,则会向您发送 400 代码

More on 400 error

【讨论】:

  • 我也会发送该路由的后端代码,请告诉我哪里出错了
  • 将您的请求包装在 try/catch 中并控制错误,我想你会明白的
【解决方案2】:

你没有处理handlesubmit中的错误

在使用 Promise 时,如果您正在使用 await,请使用 try-catch,或者使用 thencatch 正确处理 Promise 拒绝。

在您的代码中,axios 将在 http 代码 400 的情况下拒绝承诺,并且您没有在任何地方处理该错误,因此 await axios.post(${HOST}/api/auth/login, data, config); 之后的任何代码都不会运行。

使用 try-catch 正确处理该错误。

handleSubmit = async (evt) => {
        evt.preventDefault();
        try {
            const config = { headers: { "Content-Type": "application/json" } };
            const data = JSON.stringify({ username, password });
            console.log(data);
            const response = await axios.post(`${HOST}/api/auth/login`, data, config);
            console.log(response.data);
            resetUsername();
            resetPassword();
        } catch (err) {
            // do something when error occurrs
            console.log(err);
        }
    };

【讨论】:

  • 兄弟我用 try 和 catch 但进一步的程序代码 usernameReset 和 passwordReset 函数也没有被执行
猜你喜欢
  • 2021-03-17
  • 2019-08-03
  • 1970-01-01
  • 2021-04-12
  • 2021-07-09
  • 2021-06-11
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多