【问题标题】:Send data AJAX to RequestBody发送数据 AJAX 到 RequestBody
【发布时间】:2019-06-29 07:41:16
【问题描述】:

这是一件简单的事情,但因此很难。我知道它会很容易解决,但我不能轻易找到它。感谢您的帮助。

这是我的代码:

var sample = {
    query: "kakao",
    x: "127.06283102249932",
    y: "37.514322572335935",
    radius: "20000"
};

$('#search').click(function (e) {
    $.ajax({
        url: "/map/search",
        contentType: 'application/json; charset=utf-8',
        dataType: "text",
        data: JSON.stringify(sample),
        success: function(data) {
            console.log(data);
        },
        error: function(error) {
            console.log(error);
        }
    })
});

它已连接到

http://localhost:8080/map/search?{%22query%22:%22kakao%22,%22x%22:%22127.06283102249932%22,%22y%22:%2237.514322572335935%22,%22radius%22:%2220000%22}

我想发送到请求正文而不是 url 参数。这是什么问题?


编辑1

很抱歉提出更多问题。 我解决了上面的问题,又出现了新的问题。我的 Spring 服务器响应我 400 Bad Request。

这是我的java源码:

@RestController
@RequestMapping("/map")
public class MapSearchController {

    @Autowired
    private RestApiAccessor restApiAccessor;

    @RequestMapping(method = RequestMethod.GET, value = "/search")
    public MapSearchResponseDTO mapSearchRequest(@RequestBody MapSearchRequestDTO mapSearchRequestDTO) throws Exception {
        if (Objects.isNull(mapSearchRequestDTO.getQuery()))
            throw new IllegalAccessException("There is no Query parameter.");

        return restApiAccessor.mapSearchRequestGet(mapSearchRequestDTO);
    }
}

@Getter
@Setter
@ToString
public class MapSearchRequestDTO {
    private String query;
    private String category_group_code;
    private String x;
    private String y;
    private Integer radius;
    private String rect;
    private Integer page;
    private Integer size;
    private String distance;
}

我的错误:

2019-06-29 16:54:31.397  WARN 99354 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public map.search.dto.MapSearchResponseDTO map.search.controller.MapSearchController.mapSearchRequest(map.search.dto.MapSearchRequestDTO) throws java.lang.Exception]

【问题讨论】:

    标签: javascript jquery ajax object


    【解决方案1】:

    指定使用body 选项 - GET 默认使用查询参数。

    body: JSON.stringify(sample),
    

    【讨论】:

    • GET 没有请求正文吗?
    • 有没有办法用 GET 做到这一点?这是因为它是从 REST API 服务器中选择的请求。
    • 更改了@윤현구,这对你有用吗? (只需在您的代码中将data 替换为body)。
    • 是的,我解决了这个问题,谢谢。这是另一个问题,现在 BadRequest400 将开始进入服务器。好像对象没有映射。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2014-05-19
    相关资源
    最近更新 更多