如何使用ReactJS进行发布请求

时间:2020-03-04 19:36:43

标签: javascript reactjs

嗨,我是ReactJS的学生开发人员。我正在尝试学习如何使用Reactjs Context Api进行编码。当我从表单中发送类别数据时,遇到了这样的错误

未处理的拒绝(TypeError):无法在以下位置执行“提取” “窗口”:使用GET / HEAD方法的请求不能包含正文。

这是什么意思?当我执行此过程时,我在想什么?令人欣慰的代码包括我的方法。

我的上下文部分:

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;

我的类别添加组件:

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;

2 个答案:

答案 0 :(得分:3)

发生错误的原因是因为默认情况下,提取会发送GET请求,该请求不允许将正文作为请求的一部分。您需要指定访存方法为POST

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

答案 1 :(得分:3)

您正在发送GET类型请求,并且此方法未使用POST或PATCH之类的正文...

请通过

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

如果要使用GET发送内容,则必须在URL中发送