axios response.data 包含一个错误,虽然数据似乎是正确的

Axios response.data comprises an error, although the data seems to be correctly

目前我正在学习编码并想将数据发送到 MongoDb。当我控制台记录 goalData 时,内容是我在输入字段中输入的正确内容,但记录 response.data,显示以下内容:{message: 'Unexpected token " in JSON at position 0', stack: 'SyntaxError: Unexpected token " in JSON at positio…ejections (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;
}

这是我的 goalsSlice,也许这样更清楚:

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

我的Server.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);