2

Hi I am student developer at ReactJS. I am trying to learn how to code with Reactjs Context Api. When I send a data from my form for categories, I am facing an error like this

Unhandled Rejection (TypeError): Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

What is the meaning of this? What i am mising when I do this process? Fallowing code includes my methods.

my context part :

import React, { Component } from 'react';

const CapsuleContext =  React.createContext();

const reducer = (state,action)=>{
switch (action.type) {
      case "SAVE_CATEGORY_TO_API":
        fetch("http://localhost:3000/categories/", {
          headers: { "content-type": "application/json",
          "Accept":"application/json" },
          body: JSON.stringify(action.payload)
        })
        break;


    default:

    return state
}
}

export class CapsuleProvider extends Component {
    state = {
        categories: [],
        apiUrl: "http://localhost:3000/",
        dispatch : action => {
          this.setState(state => reducer(state,action))
        }

      }

      getCategories = () => {
        fetch(this.state.apiUrl + "categories")
          .then(res => res.json())
          .then(data => this.setState({ categories: data }));
      }



    render() {
        return (
            <CapsuleContext.Provider value = {this.state}>
                {this.props.children}
            </CapsuleContext.Provider>
        );
    }
}
const CapsuleConsumer = CapsuleContext.Consumer;

export default CapsuleConsumer;

my categoryAdd component :

import React, { Component } from 'react';
import { Button, Form, FormGroup, Label, Input, ListGroup, ListGroupItem } from 'reactstrap';
import { Link } from "react-router-dom"
import CapsuleConsumer from '../../context/Context';
import CategoryList from './CategoryList';

class CategoryAdd extends Component {


    handleChange = (event) => {
        let value = event.target.value;
        let name = event.target.name;
        this.setState({ [name]: value })
    }

    handleSubmit = (event) => {
        event.preventDefault();

    }
    saveCategory = (event, dispatch) => {
        dispatch({ type: "SAVE_CATEGORY_TO_API", payload: {id : event.state.id , categoryName : event.state.categoryName , seoUrl:event.state.seoUrl}})
    }



    render() {
        return (
            <CapsuleConsumer>
                {
                    value => {

                        const { categories, dispatch } = value;
                        return (
                            <div>


                                <div>

                                    <Form className="mt-3  font-weight-bold" onSubmit={this.handleSubmit}>
                                        <FormGroup className="text-left">
                                            <Label for="id">Category Id</Label>
                                            <Input type="text"
                                                name="id"
                                                onChange={this.handleChange}
                                                placeholder={categories.length + 1}
                                            />
                                        </FormGroup>
                                        <FormGroup className="text-left">
                                            <Label for="categoryName">Category Name</Label>
                                            <Input type="text"
                                                name="categoryName"
                                                onChange={this.handleChange}
                                                placeholder="enter a category name" />
                                        </FormGroup>
                                        <FormGroup className="text-left">
                                            <Label for="seoUrl">Seo Url</Label>
                                            <Input type="text"
                                                name="seoUrl"
                                                onChange={this.handleChange}
                                                placeholder="enter a seo url" />
                                        </FormGroup>
                                        <Button color="success" onClick={() => this.saveCategory(this, dispatch)} type="submit">Submit</Button>
                                    </Form>
                                </div>                      
                            </div>
                        )
                    }}
            </CapsuleConsumer>

        );
    }
}
export default CategoryAdd;
1
  • You can't send a body with a GET request. Commented Mar 4, 2020 at 19:45

2 Answers 2

3

The reason for your error is because fetch sends a GET request by default which does not allow a body as part of the request. You need to specify that the fetch method is POST:

fetch("http://localhost:3000/categories/", {
  method: "POST",
  headers: { 
    "Content-Type": "application/json",
    "Accept":"application/json"
  },
  body: JSON.stringify(action.payload)
})
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot. I was missing part of method : 'Post'. I realized it now.
3

You are sending a GET type request and this method does not use body like POST or PATCH...

Please check your code at

fetch("http://localhost:3000/categories/", {
      headers: { "content-type": "application/json",
      "Accept":"application/json" },
      body: JSON.stringify(action.payload)
    })

if you are going to send something using GET must send it in the URL

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.