zoukankan      html  css  js  c++  java
  • postman测试接口,后台请求正常但返回404错误

      今天用postman工具测试接口时,返回404错误,花费很久时间处理,之前用了这么久的工具不至于出错,只可能程序出错了。

    报错信息:

    {
        "timestamp": "2021-08-18T11:46:43.469+0000",
        "status": 404,
        "error": "Not Found",
        "message": "No message available",
        "path": "/data/test"
    }
    后台程序看接口访问正常,可以正常输出日志,但是到postman工具中就报404错误
    最终排查下来是缺少了@ResponseBody 注解。

    @ResponseBody

    来看看为什么要添加这个注解

      The course documentation states that this annotation serves the function to: ensure that the result will be written to the HTTP response by an HTTP Message Converter (instead of an MVC View).

      The annotation means is that the returned value of the method will constitute the body of the HTTP response.

      The returned value of the method will constitute the body of the HTTP response.

      说的就是一个意思,就是 @ResponseBody 用于对方法进行注释, 表示该方法的返回的结果将直接写入 HTTP 响应正文(Http Response Body)中。我之前控制层代码里有返回值,类型为 CommonReturnType 的通用返回值类型,我把返回值去掉后,方法改为 void,无任何返回值, 虽然在前端的调试中,各种数据依然正常,但是前端页面获取不到控制层方法的返回值,在 response body 中无内容,导致点击前端页面的按钮不会有任何现象发生,虽然此时后端逻辑正确无误,请求也成功了,后端程序正常运行,数据库入库操作都实现了,但是前端获取不到呀。所以我这里必须给该方法一个返回值,且要通过注解形式将返回值加到 Http response body 中。 如果没有这个注解,就会抛出上面的 responseText 异常信息。

    附正确的用法:

    import com.gdiot.model.CommonResult;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Slf4j
    @Controller
    @RequestMapping("/data")
    @ResponseBody
    public class TestController {

    @RequestMapping("/test")
    public String test_get(){
    log.info(String.format("test_get"));
    return "test_get";
    }
    }
  • 相关阅读:
    十一月计划
    归并排序+例题
    今年暑假不AC(简单贪心)
    路障(BFS)
    堆优化版Dijkstra模板
    十月计划
    Find a way(BFS)
    Prime Path(BFS)
    Find The Multiple
    k8s中node节点资源不足
  • 原文地址:https://www.cnblogs.com/zjqlogs/p/15158573.html
Copyright © 2011-2022 走看看