axios 如何使用Express和React调试400错误

k97glaaz  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(125)

我在浏览器控制台中得到了这个:

`xhr.js:251     POST http://localhost:325/budget 400 (Bad Request)

BudgetNew.js:30 catch AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}`

以下是我的服务器端代码:

budget_controller:

//DEPENDENCIES
const express = require("express");
const budget = express.Router();
const budgetArray = require("../models/budget_table.js");
const { validateBudgetData } = require("../models/validations.js");

//CONFIGURATION
budget.get('/', (req, res) => {
    res.json(budgetArray);
});
/* this route is triggered when a "GET" request is made to the base URL ("/budget"). It responds by sending the entire budgetArrau as a JSON in the res body - this retrieves a list of items in the budget array
*/

//with error handling:
budget.get("/:arrayIndex", (req,res) => {
    if(budgetArray[req.params.arrayIndex]) {
        res.json(budgetArray[req.params.arrayIndex]);
    } else {
        res.status(404).json({error: "Not Found"});
    }
});

budget.post("/", validateBudgetData, (req, res) => {
    budgetArray.push(req.body);
    res.json(budgetArray[budgetArray.length - 1])
});

//DELETE with error handling
budget.delete("/:indexArray", (req, res) => {
    if (budgetArray[req.params.indexArray]) {
        const deletedItem = budgetArray.splice(req.params.indexArray, 1);
        res.status(200).json(deletedItem);
    } else {
        res.status(404).json({ error: "Not Found" });
    }
})

//UPDATE/change already existing data (HTTP verb PUT) with error handling
budget.put("/:arrayIndex", validateBudgetData, async (req, res) => {
    if (budgetArray[req.params.arrayIndex]) {
        budgetArray[req.params.arrayIndex] = req.body; 
        res.status(200).json(budgetArray[req.params.arrayIndex]);
    } else {
        res.status(404).json({ error: "Not found" })
    }
});


//EXPORT
module.exports = budget;

验证:

const validateBudgetData = (req, res, next) => {
    const { item_name, amount, deduction, date, category } = req.body;

    if (
        typeof item_name === 'string' &&
        typeof amount === 'number' &&
        typeof deduction === 'boolean' &&
        typeof date === 'string' &&
        typeof category === 'string'
    ) {
        return next();
    } else {
        res.status(400).send("Invalid budget data");
    }
};

//EXPORT
module.exports = { validateBudgetData };

REACT预算新组件

import { useState } from "react";
import { useNavigate, Link, useParams } from "react-router-dom";
import axios from "axios";

export default function BudgetNew() {
    const API = process.env.REACT_APP_API_URL;
    const navigate = useNavigate();
    const { index } = useParams(); //Get the index parameter from the URL
    const [transaction, setTransaction] = useState({
        item_name: "",
        amount: 0,
        date: "",
        deduction: false,
        category: "",
    });

    const handleTextChange = (e) => {
        setTransaction({ ...transaction, [e.target.id]: e.target.value });
    };

    const handleCheckboxChange = () => {
        setTransaction({ ...transaction, deduction: !transaction.deduction });
    };

    const addTransaction = (newTransaction) => {
        axios
        .post(`${API}/budget`, newTransaction)
        .then(() => {
            navigate("/budget");
        })
        .catch((c) => console.error("catch", c));
    };
    /* the addTransaction fxn takes 2 parameters:
    // 1.the URL where the request will be sent 
    // 2. newTransaction, a variable that represents the data of the new transaction to be added to the server
    // */

    const handleSubmit = (e) => {
        e.preventDefault();
        addTransaction(transaction);
        //call the addTransaction fxn with the transaction data and not "newTransaction" because the form data is stored in transaction from our useState fxn not "newTransaction". So, when we want to call the addTransaction fxn, we should pass the transaction data as an argument.
    }

    return (
            <div className="Edit">
                <form onSubmit={handleSubmit}>
                    <label htmlFor="name">Name:</label>
                    <input
                        id="item_name"
                        value={transaction.item_name}
                        type="text"
                        onChange={handleTextChange}
                        placeholder="Item name"
                        required
                    />
                    <label htmlFor="amount">Amout:</label>
                    <input
                        id="amount"
                        value={transaction.amount}
                        type="number"
                        onChange={handleTextChange}
                        placeholder="Enter amount"
                        required
                    />
                    <label htmlFor="deduction">Is this transaction a deduction?</label>
                    <p>Does this take away from total income? If yes, check the box. If no, leave box unchecked.</p>
                    <input
                        id="deduction"
                        value={transaction.deduction}
                        type="checkbox"
                        onChange={handleCheckboxChange}
                    />
                    <br />

                    <label htmlFor="date">Date:</label>
                    <p>Enter as mm/dd/yyyy</p>
                    <input
                        id="date"
                        value={transaction.date}
                        type="text"
                        onChange={handleTextChange}
                        placeholder="Date of transaction"
                        // required
                    />
                    <label htmlFor="category">Category: </label>
                    <input
                        id="category"
                        value={transaction.category}
                        type="text"
                        onChange={handleTextChange}
                        placeholder="What is this for?"
                        required
                    />
                    <br />
    
                    <input type="submit" />
                </form>
                <Link to={`/budget/${index}`}>
                    <button>Nevermind!</button>
                </Link>
            </div>
    );
}

我试着重新启动启动和React应用程序。我检查了代码。我在BudgetNew组件中注解掉了我的“addTransaction”fxn,并添加了以下代码:

const requestData = {
    item_name: "Cash",
    amount: 100,
    deduction: false,
    date: "07/30/23",
    category: "income"
};

axios.post(`${API}/budget`, requestData)
    .then((response) => {
        console.log("Success:", response.data);
    })
    .catch((error) => {
        console.log("Error:", error.response.data);
    });

这工作,这暗示服务器端不是问题,但我仍然得到错误。

8i9zcol2

8i9zcol21#

第一个问题:
我能看看你的.env文件吗?
您发布的错误引用了API变量,该变量由.env文件中的“REACT_APP_API_URL”变量定义。
你真的在localhost:325上运行应用程序吗?
只是好奇,我从来没有在那个端口上运行过react应用程序或服务器。
我会仔细检查REACT_APP_API_URL的值在客户端的.env中是否正确(我假设客户端和服务器有单独的.env文件)
如果没有看到.env文件,很难判断你的错误真正来自哪里。
编辑:我认为这可能是问题的原因是错误消息指出这是一个错误的请求,所以看起来你的请求甚至没有到达你的服务器。

相关问题