代码之家  ›  专栏  ›  技术社区  ›  techie_questie

在AXIOS中发送GET方法的请求正文会引发错误

  •  0
  • techie_questie  · 技术社区  · 6 年前

    我有一个React应用程序,其中我正在更改POST方法,以使请求体保持原样。它可以很好地处理POST请求,但是当我更改获取方法时,它会给我错误-

    message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public 
    

    我的前端代码-

    export const setData = (getData)  => dispatch => {
        axios({
            method: 'GET',
            url: 'http://localhost:8080/api',
            headers: {
              'Content-Type': 'application/json'
            },
            data: getData
          })
          .then (response => {
          dispatch({
            type: API_DATA, 
            payload: response.data
          })
          dispatch({
            type: SET_SEARCH_LOADER, 
            payload: false
          })
          })
          .catch(function(error) {       
          })
    }
    

    有人能告诉我我错过了什么吗。根据我的理解,http允许GET方法有一个请求体。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Amirrossein Sadeghi    5 年前

    如果要在axios中使用get请求发送参数,则应按以下方式发送参数: params .

    如果你想设置 "Content-type":"application/json" 和使用get请求发送参数,还应发送一个空 data 对象

    例如:

    const AUTH_TOKEN = 'Bearer token'
    const config = {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': AUTH_TOKEN,
        },
        data: {},
        params: {
            "post_id": 1
        }
    }
    axios.get("http://localhost/api/v1/posts/", config)
    
        2
  •  1
  •   Quentin    6 年前

    根据我的理解,http允许GET方法有一个请求体。

    虽然这在技术上是正确的(虽然更准确地说,它只是没有明确地禁止它),但这是一件非常奇怪的事情,而且大多数系统都不希望GET请求有实体。

    因此,很多图书馆不会处理这个问题。

    这个 documentation for Axois 说:

      // `data` is the data to be sent as the request body
      // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
    

    the specification for that 它说:

    client . send([body = null])

    启动请求。body参数提供请求主体(如果有),并且 如果请求方法为GET,则忽略 或者头部。

        3
  •  0
  •   Fred    6 年前

    这不是axios,错误源于您正在与之交谈的java后端。请求正文中缺少公共字段。

    params 而不是 data https://github.com/axios/axios#example ).

    我个人认为您的API不应该支持请求主体的GET(与开发人员交谈并要求提供文档)。