javascript HTTP PUT请求在控制台中返回400错误请求

qxsslcnc  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(375)

我尝试使用strapi作为REST API来制作一个react crud应用程序,get,delete和create都工作正常,但当我发出PUT请求时,我得到了一个400错误的请求。我使用redux toolkit和useContext来管理状态。看看,我已经创建了usePetContext和store。我是第一次使用react
PUT页面

import React, { useState, useEffect } from 'react';
    
// mui components
import {
    Typography,
    TextField,
    Box,
    Button,
    Paper
} from '@mui/material';

// mui icons
import { Edit } from '@mui/icons-material';

// custom components
import BottomNav from './BottomNav';

import { useUpdatePetMutation } from '../services/petApi';
import Loader from './Loader';
import { useParams } from 'react-router-dom';
import { usePetContext } from '../petContext';

export default function EditPetEntry() {
    // input data
    const [name, setName] = useState("");
    const [animal, setAnimal] = useState("");
    const [breed, setBreed] = useState("");
    const [age, setAge] = useState("");
    const [location, setLocation] = useState("");
    const [sex, setSex] = useState("");
    const {id} = useParams();
    const { petId } = usePetContext();
    // edit req
    const [updatePet, { isLoading }] = useUpdatePetMutation();
    const data = JSON.stringify({
        "data": {
            "name": name,
            "animal": animal,
            "breed": breed,
            "age": age,
            "location": location,
            "sex": sex
        }
    });
    const handleEditPet = () => {
        updatePet(petId, data);
    };

    console.log(typeof petId);

    return (
        <Box
            component="form"
            sx={{
                '& .MuiTextField-root': { m: 1, width: '50ch' },
                display: 'flex',
                flexDirection: 'column'
            }}
            noValidate
            autoComplete="off"
        >
            <div>
                <Typography variant="h3" gutterBottom component="div">
                    Edit Pet entry
                </Typography>
                <TextField
                    required
                    id="filled-name"
                    label="Name"
                    variant="outlined"
                    onChange={(e)=>setName(e.target.value)}
                />
                <TextField
                    required
                    id="filled-animal"
                    label="Animal"
                    variant="outlined"
                    helperText="Cat, Dog, Bird"
                    onChange={(e)=>setAnimal(e.target.value)}
                />
                <TextField
                    required
                    id="filled-breed-input"
                    label="Breed"
                    variant="outlined"
                    onChange={(e)=>setBreed(e.target.value)}
                />
                <TextField
                    required
                    id="filled-location-input"
                    label="Location"
                    variant="outlined"
                    onChange={(e)=>setLocation(e.target.value)}
                />
                <TextField
                    required
                    id="filled-age"
                    label="Age"
                    type="number"
                    variant="outlined"
                    onChange={(e)=>setAge(e.target.value)}
                />
                <TextField
                    required
                    id="sex"
                    label="Sex"
                    helperText="Male, Female"
                    variant="outlined"
                    onChange={(e)=>setSex(e.target.value)}
                />
            </div>
            <div>
                <Button variant="outlined" onClick={handleEditPet} startIcon={<Edit />}>
                    Edit Pet Entry
                </Button>
                {isLoading && <Loader />}
            </div>
            <Paper sx={{ position: 'fixed', bottom: 0, left: 0, right: 0 }} elevation={3}>
                <BottomNav/>
            </Paper>
        </Box>
    );
}

app.js

import React, {useState} from 'react';
import './App.css';
import BottomNav from '../src/components/BottomNav';
import {
  Routes,
  Route,
} from "react-router-dom";
import PetList from '../src/components/PetList';
import CreatePetEntry from '../src/components/CreatePetEntry';
import EditPetEntry from '../src/components/EditPetEntry';
import PetListItem from './components/PetListItem';

function App() {

  return (
    <div className="App">
      <h1>Pet Adoption</h1>
      <div>
          <Routes>
            <Route exact path="/" element={ <PetList /> } />
            <Route exact path="/addpet" element={ <CreatePetEntry /> } />
            <Route exact path="/editpet/:id" element={ <EditPetEntry /> } />
          </Routes>
      </div>
      <BottomNav />
    </div>
  );
}

export default App;

petApi.js

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const petApiHeaders = {
    "Content-type": "application/json",
};

const baseUrl = 'http://localhost:1337/api/';

const createRequest = (url) => ({ url, headers: petApiHeaders });

export const petApi = createApi({
  reducerPath: 'petApi',
  baseQuery: fetchBaseQuery({ baseUrl }),
  tagTypes: ['Pet'],
  endpoints: (builder) => ({
    getPets: builder.query({
      query: () => createRequest('pets'),
      providesTags: ['Pet'],
    }),
    addNewPet: builder.mutation({
      query: (payload) => ({
        url: 'pets',
        method: 'POST',
        body: payload,
        headers: {
          'Content-type': 'application/json; charset=UTF-8',
        },
      }),
      invalidatesTags: ['Pet'],
    }),
    updatePet: builder.mutation({
      query: (id, payload) => ({
        url: `/pets/${id}`,
        method: 'PUT',
        body: payload,
        headers: {
          'Content-type': 'application/json; charset=UTF-8',
        },
      }),
      invalidatesTags: ['Pet'],
    }),
    deletePet: builder.mutation({
      query: (id) => ({
        url: `pets/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: ['Pet'],
    }),
  })
})

export const {
    useGetPetsQuery,
    useAddNewPetMutation,
    useUpdatePetMutation,
    useDeletePetMutation,
  } = petApi;

petContext.js

import React, { createContext, useContext, useEffect, useState } from 'react';

const PetContext = createContext();

export const usePetContext = () => {
    return useContext(PetContext);
};

export const PetProvider = ({children}) => {
    const [petId, setPetId] = useState('');

    // get pet id value
    const getPetId = (id) => {
        setPetId(id);
    };

    const value = {
        getPetId,
        petId
    };

    // context provider
    return(
        <PetContext.Provider value={value}>
            {children}
        </PetContext.Provider>
    )
};

如果您需要更多信息来诊断问题,请联系我们,我正在使用reactrouter 6和redux工具包重新创建this教程

nr9pn0ug

nr9pn0ug1#

很难确定在您的特定情况下出了什么问题。但是,有一些通用的步骤可以使调试问题变得更容易
1.您可以在Google Chrome DevTools https://developer.chrome.com/docs/devtools/network/中检查实际的请求/响应是什么这是一个完整的文档指南。但是,您可以通过单击带有错误的行来查看相关信息(PUT请求在您的情况下).在那里你会看到什么是你发送的数据,最有可能有一些东西丢失.这可能是一个很好的开始.也许ID没有填充出于某种原因,也许是什么东西是不正确的有效载荷等?这将有助于您进一步调试它。
1.您也可以从服务器日志中获得类似的信息。检查您在服务器上接收到的内容很有帮助。不确定这是您的本地服务器还是prod服务器。

相关问题