首页 > 解决方案 > React 在 PUT 上发送一个空的 JSON 对象

问题描述

我正在尝试向我创建的 REST 服务器发送 PUT 请求,但无论我做什么,发送的 JSON 对象都是空的。我已经在 Postmaster 中尝试过服务器,它按预期工作,所以问题一定出在 React 应用程序上。

这是发送请求的函数:

    handleSubmit(e) {
        e.preventDefault();
        const newBrand = this.state.brand
        newBrand.description = this.state.editorState.getCurrentContent().getPlainText()
        const json = JSON.stringify(newBrand)
        console.log(json)
        axios.put(`http://localhost:8080/BackendWiki/api/brands/${this.props.brandName}`, {json})
            .then(res => {
                console.log(res);
                console.log(res.data);
            })
    }

打印到控制台的子对象如下所示:

{"id":56,"created":1597255927810,"updated":1597255927810,"links":[{"href":"http://localhost:8080/BackendWiki/api/brands/rolex","rel":"self","action":"GET"},{"href":"http://localhost:8080/BackendWiki/api/brands/rolex","rel":"self","action":"DELETE"},{"href":"http://localhost:8080/BackendWiki/api/brands/rolex","rel":"self","action":"PUT"}],"name":"Rolex","founded":0,"founder":null,"ceo":null,"headQuarters":null,"description":"more, more, more","text":[]}

我已经实现了一个正常工作的 get 请求,如下所示:

    componentDidMount() {
        Axios.get("http://localhost:8080/BackendWiki/api/brands/")
            .then(res => {
                const brands = res.data;
                this.setState({brands})
            })
    }

下面是处理 PUT 请求的代码:

 @PUT
    @Path("/{name}")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response updateBrand(@PathParam("name") String name, Brand updateBrand) {
        System.out.println(updateBrand);
        Brand oldBrand = brandDAO.getBrandByName(name.replaceAll("-", " "));
        if (oldBrand != null) {
            updateBrand.setId(oldBrand.getId());
            brandDAO.update(updateBrand);
            return Response
                    .status(200)
                    .entity(brandDAO.getBrandById(updateBrand.getId()))
                  //  .header("Access-Control-Allow-Origin", "*")
                    .build();
        } else {
            return Response
                    .status(404)
                    //.header("Access-Control-Allow-Origin", "*")
                    .build();
        }
    }

我也没有收到任何错误消息,所以我对为什么 PUT 不起作用感到有些困惑。任何帮助将非常感激。

标签: jsonreactjsrestaxios

解决方案


推荐阅读