我用Postman测试了所有的CRUD操作,甚至POST,但只有POST在前端应用程序中不起作用,我已经调试了几个小时,但我得到了错误。
Uncaught(in promise)AxiosError {message:'请求失败,状态代码为500',名称:“AxiosError”,代码:'ERR_BAD_RESPONSE',配置:{...},请求:XMLHttpRequest,...}代码:“ERR_BAD_RESPONSE”配置:{过渡:{...},适配器:Array(2),transformRequest:Array(1),transformResponse:数组(% 1),超时:0,...}消息:“请求失败,状态代码为500”名称:“AxiosError”请求:XMLHttpRequest {onreadystatechange:null,readyState:4、超时:0,withCredentials:false,upload:XMLHttpRequestUpload,...}响应:{数据:{...},状态:500,状态文本:'',标题:AxiosHeaders,配置:{...},...}堆栈:“AxiosError:请求失败,状态代码为500\n,位于settle(webpack-internal:///(app-client)/./node_modules/axios/lib/core/settle.js:24:12)\n,位于XMLHttpRequest.onloadend(webpack-internal:///(app-client)/./node_modules/axios/lib/adapters/xhr.js:121:66)"Prototype:错误
这是我的代码
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const url = "https://leader-board-backend.vercel.app/api/v1/score/";
const initialState = {
details: [],
isLoading: true,
};
export const getScores = createAsyncThunk("score/getScores", async () => {
try {
const { data } = await axios(url);
console.log(`SERVER DATA`);
console.log(data);
return data;
} catch (error) {
console.log(error.response);
throw error;
}
});
const scoreSlice = createSlice({
name: "score",
initialState,
reducers: {
addDetails: {
reducer(state, action) {
state.details.push(action.payload);
},
prepare(name, exactScore) {
return {
payload: {
name,
exactScore,
},
};
},
},
updateDetails(state, action) {
const { _id, ...formData } = action.payload;
state.details = state.details.map((item) =>
item._id === _id ? { ...item, ...formData } : item
);
},
deleteDetails: (state, action) => {
const id = action.payload;
state.details = state.details.filter((item) => item._id !== id);
},
},
extraReducers(builder) {
builder
.addCase(getScores.pending, (state) => {
state.isLoading = true;
})
.addCase(getScores.fulfilled, (state, action) => {
state.isLoading = false;
state.details = action.payload;
})
.addCase(getScores.rejected, (state) => {
state.isLoading = false;
});
},
});
export const isLoading = (state) => state.isLoading;
export const { addDetails, deleteDetails, updateDetails } = scoreSlice.actions;
export default scoreSlice.reducer;
import axios from "axios";
import { useDispatch } from "react-redux";
import { useState } from "react";
import {
deleteDetails,
updateDetails,
} from "../store/features/score/scoreSlice";
export const Score = ({ _id, name, exactScore }) => {
const dispatch = useDispatch();
const [editMode, setEditMode] = useState(false);
const [formdata, setFormData] = useState({
name: name,
exactScore: exactScore,
});
async function handleDelete() {
const url = `https://leader-board-backend.vercel.app/api/v1/score/${_id}`;
try {
const { data } = await axios.delete(url);
dispatch(deleteDetails(_id));
return data;
} catch (error) {
console.log(error.response);
throw error;
}
}
function handleEdit() {
setEditMode(!editMode);
}
function handleChange(event) {
const { name, value } = event.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
}
async function handleSubmit(event) {
event.preventDefault();
const url = `https://leader-board-backend.vercel.app/api/v1/score/${_id}`;
try {
await axios.patch(url, formdata);
dispatch(updateDetails({ _id, ...formdata }));
setEditMode(false);
} catch (error) {
console.log(error.response);
throw error;
}
}
return (
<div>
{editMode ? (
<form onSubmit={handleSubmit}>
<label htmlFor="name" className="form-label">
Name
</label>
<input
type="text"
id="name"
name="name"
value={formdata.name}
onChange={handleChange}
className="form-control"
aria-describedby="name"
/>
<label htmlFor="exactScore" className="form-label">
Score
</label>
<input
type="text"
id="exactScore"
name="exactScore"
value={formdata.exactScore}
onChange={handleChange}
className="form-control"
aria-describedby="exactScore"
/>
<button type="submit" className="btn btn-success mt-1">
Save
</button>
</form>
) : (
<div
className="card text-left my-2"
style={{ backgroundColor: "white" }}
>
<div className="row card-body">
<div className="col">
<p style={{ margin: 0, padding: 0 }}>{name}</p>
</div>
<div className="col">
<p style={{ margin: 0, padding: 0 }}>{exactScore}</p>
</div>
<div className="col col-lg-2">
<button
onClick={handleEdit}
className="me-3 rounded-circle bg-success border border-0 text-light"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
fill="currentColor"
class="bi bi-pencil-square"
viewBox="0 0 16 16"
>
<path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
<path
fill-rule="evenodd"
d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"
/>
</svg>
</button>
<button
onClick={handleDelete}
className="mx-3 rounded-circle bg-danger border border-0 text-light"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
fill="currentColor"
class="bi bi-trash"
viewBox="0 0 16 16"
>
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6Z" />
<path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1ZM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118ZM2.5 3h11V2h-11v1Z" />
</svg>
</button>
</div>
</div>
</div>
)}
</div>
);
};
import { useSelector } from "react-redux";
import { Score } from "./Score";
export const ScoreContainer = () => {
const data = useSelector((state) => state.score.details);
const m = data.map((value) => (
<Score
key={value._id}
_id={value._id}
name={value.name}
exactScore={value.exactScore}
/>
));
return <div>{m}</div>;
};
import { useState } from "react";
import axios from "axios";
import { useDispatch } from "react-redux";
import { addDetails } from "../store/features/score/scoreSlice";
export const PostScore = () => {
const dispatch = useDispatch();
const [formdata, setFormData] = useState({
_id: "",
name: "",
exactScore: "",
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
}
async function handleSubmit(event) {
event.preventDefault();
const url = "https://leader-board-backend.vercel.app/api/v1/score/";
try {
const { data } = await axios.post(url, formdata);
dispatch(addDetails(data.name, data.exactScore));
} catch (error) {
console.log(error.response);
throw error;
}
setFormData({ name: "", exactScore: "" });
}
return (
<form
className="py-3 d-flex justify-content-center align-items-center gap-3"
style={{ boxSizing: "border-box" }}
>
<label htmlFor="name" className="fw-bold form-label">
Name
</label>
<input
type="text"
id="name"
name="name"
onChange={handleChange}
className="form-control"
aria-labelledby="name"
/>
<label htmlFor="exactScore" className="fw-bold form-label">
Score
</label>
<input
type="text"
id="exactScore"
name="exactScore"
onChange={handleChange}
className="form-control"
aria-labelledby="exactScore"
/>
<button
type="submit"
onClick={handleSubmit}
className="btn btn-primary rounded-pill fw-bold"
style={{ width: "24rem" }}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
fill="currentColor"
class="bi bi-plus-lg"
viewBox="0 0 16 16"
style={{ color: "white" }}
className="text-white"
>
<path
fill-rule="evenodd"
d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2Z"
style={{ color: "white" }}
className="text-white"
/>
</svg>
Post
</button>
</form>
);
};
UPDATE*不是服务器错误,而是这里**
async function handleSubmit(event) {
event.preventDefault();
const url = "https://leader-board-backend.vercel.app/api/v1/score/";
try {
const { data } = await axios.post(url, formdata);
dispatch(addDetails(data.name, data.exactScore));
} catch (error) {
console.log(error.response);
throw error;
}
setFormData({ name: "", exactScore: "" });
}
以及如何发送这些数据
const [formdata, setFormData] = useState({
_id: "",
name: "",
exactScore: "",
});
当我将每个转换为单个状态时。
const [name, setName] = useState("");
const [exactScore, setExactScore] = useState("");
function handleNameChange(event) {
setName(event.target.value);
}
function handleScoreChange(event) {
setExactScore(event.target.value);
}
async function handleSubmit(event) {
event.preventDefault();
const url = "https://leader-board-backend.vercel.app/api/v1/score/";
try {
const { data } = await axios.post(url, { name, exactScore });
dispatch(addDetails(data.name, data.exactScore));
} catch (error) {
console.log(error.response);
throw error;
}
setName("");
setExactScore("");
}
它工作得很好,但在其他部分(如编辑和删除)会导致错误
1条答案
按热度按时间ljo96ir51#
问题解决了我必须删除_id:“",因为它最初并不存在,而是由数据库创建的。