Axios response.data包含一个错误,尽管数据似乎是正确的



目前我正在学习编码,并希望将数据发送到MongoDb。当我控制台日志goalData时,内容与我在输入字段中输入的内容正确,但记录response.data时,显示以下内容:{message:"位置0处JSON中的意外令牌",stack:"SyntaxError:位置弹出处JSON中意外令牌"(internal/process/task_queues.js:82:21(}。我的数据库中没有条目。这是我的代码:

const createGoal = async (goalData, token)=>{
const config = {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
}
console.log(config);
console.log(goalData);
const response = await axios.post(API_URL, goalData, config);
console.log(response.data);
return response.data;
}

这是我的目标Slice,也许它让它更清楚:

import {createSlice, createAsyncThunk} from "@reduxjs/toolkit";
import goalsService from "./goalsService";
const initialState = {
goals:[],
isLoading:false,
isError:false,
isSuccess:false,
message:"",
}
//Create new Goal
export const createGoal = createAsyncThunk('goals/create', async (goalData, thunkAPI)=>{
try{
const token = thunkAPI.getState().auth.user.token
return await goalsService.createGoal(goalData, 'utf-8', token)
}catch(error){
const message = (error.response 
&& error.response.data 
&& error.response.data.message) || error.message || error.toString()
return thunkAPI.rejectWithValue(message);
}
})
//Get Goals
export const getGoals = createAsyncThunk("goals/getAll", async (_, thunkAPI)=>{
try{
const token = thunkAPI.getState().auth.user.token
return await goalsService.getGoals(token)
} catch(error){
const message = (error.response 
&& error.response.data 
&& error.response.data.message) || error.message || error.toString()
return thunkAPI.rejectWithValue(message);
}
})
//deleteGoal
export const deleteGoal = createAsyncThunk("goals/delete", async ( id, thunkAPI)=>{
try{
const token = thunkAPI.getState().auth.user.token
return await goalsService.deleteGoal(id, token)
} catch(error){
const message = (error.response 
&& error.response.data 
&& error.response.data.message) || error.message || error.toString()
return thunkAPI.rejectWithValue(message);
}
})         
export const goalsSlice = createSlice({
name:"goals",
initialState, 
reducers: {
reset: state=>initialState
},
extraReducers: (builder)=>{
builder
.addCase(createGoal.pending, (state)=>{
state.isLoading = true;
})
.addCase(createGoal.fulfilled, (state, action)=>{
state.isLoading = false;
state.isSuccess = true;
state.goals.push(action.payload);
})
.addCase(createGoal.rejected, (state, action)=>{
state.isLoading = false;
state.isError = true;
state.message = action.payload
})
.addCase(getGoals.pending, (state)=>{
state.isLoading = true;
})
.addCase(getGoals.fulfilled, (state, action)=>{
state.isLoading = false;
state.isSuccess = true;
state.goals = action.payload
})
.addCase(getGoals.rejected, (state, action)=>{
state.isLoading = false;
state.isError = true;
state.message = action.payload
})
.addCase(deleteGoal.pending, (state)=>{
state.isLoading = true;
})
.addCase(deleteGoal.fulfilled, (state, action)=>{
state.isLoading = false;
state.isSuccess = true;
state.goals = state.goals.filter((goal)=>goal._id !== action.payload.id)
})
.addCase(deleteGoal.rejected, (state, action)=>{
state.isLoading = false;
state.isError = true;
state.message = action.payload
})
}
})
export const {reset} = goalsSlice.actions
export default goalsSlice.reducer

我的服务器.js:

const express = require("express");
const dotenv = require("dotenv").config();
const colors = require("colors");
const {errorHandler} = require("./middleware/errorMiddleware");
const connectDb = require("./config/db");
const port = process.env.PORT || 5000;
connectDb();
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use("/api/goals", require("./routes/goalRoutes"));
app.use("/api/users", require("./routes/userRoutes"));
app.use(errorHandler);
app.listen(port, ()=>console.log(`Server is running on Port ${port}`));

我的目标路线:

const express=require("express");
const router = express.Router();
const { getGoals, setGoal, updateGoal, deleteGoal } = require("../controller/goalController");
const {protect} = require("../middleware/authMiddleware");
router.route("/").get(protect, getGoals).post(protect, setGoal);
router.route("/:id").put(protect, updateGoal).delete(protect, deleteGoal);
module.exports = router;

我的目标控制器:

const asyncHandler = require("express-async-handler");
const Goal = require("../models/goalModel");
const User = require("../models/userModel");
const getGoals = asyncHandler(async (req,res)=>{
const goals = await Goal.find({ user: req.user.id });
res.status(200).json(goals);
})
const setGoal = asyncHandler(async (req,res)=>{
if(!req.body.text){
res.status(400)
throw new Error("Please add a text field");
}
const goal = await Goal.create({
text: req.body.text,
user: req.user.id
})
res.status(200).json(goal);
})
const updateGoal = asyncHandler(async (req,res)=>{
const goal = await Goal.findByIdAndUpdate(req.params.id);
if(!goal){
res.status.apply(400);
throw new Error("Goal not found");
}
if(!req.user){
res.status(401)
throw new Error("User not found");
}
if(goal.user.toString() !== req.user.id){
res.status(401)
throw new Error("Not authorized");
}
const updatedgoal = await Goal.findByIdAndUpdate(req.params.id, req.body, {new:true});
res.status(200).json(updatedgoal);
})
const deleteGoal = asyncHandler(async (req,res)=>{
const goal = await Goal.findByIdAndDelete(req.params.id);
if(!goal){
res.status(400)
throw new Error("Goal not found");
}

if(!req.user){
res.status(401)
throw new Error("User not found");
}

if(goal.user.toString() !== req.user.id){
res.status(401)
throw new Error("Not authorized");
}
await goal.deleteOne();
res.status(200).json({id: req.params.id})
})
module.exports = {
getGoals,
setGoal,
updateGoal,
deleteGoal,
}

我的目标模型:

const mongoose = require("mongoose");
const goalSchema = mongoose.Schema(
{
text: {type:String, required:true},
user:{type:mongoose.Schema.Types.ObjectId, required: true, ref:'User'},

}, {timestamps:true}
);
module.exports = mongoose.model("Goal", goalSchema);

谢谢你的帮助。

这里的问题是,您只发送了一个字符串作为axios post调用的body

至少,您的后端正在寻找一个JSON格式的对象,该对象具有名为text:的属性

const postBody = {text: goalData};
//the use that object as the body of the post call
const response = await axios.post(API_URL, postBody, config);

相关内容

最新更新