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

将@RequestBody从节点js发送到Spring Boot Rest API

  •  0
  • user1609085  · 技术社区  · 7 年前

    尝试从NodeJSto Spring Rest API发送表单数据。

    var inputData = { base : req.body.base, test : req.body.test }
    
    var queryParams = {
              host: '127.0.0.1',
              port: 8080,
              path: '/start',
              method: 'POST',
              headers: {'Content-type': 'application/json'},
              body: inputData //Used JSON.stringify(inputData) - didn't work
            };
    

    var req = http.request(queryParams, function(res) {
            //do something with response
        });
        req.end();
    

    弹簧休息:

        @RequestMapping(value = "/start", method = RequestMethod.POST, consumes = "application/json")
        @ResponseBody
        public String startApp(@RequestBody String body) {
            System.out.println(body);
    
            return "{\"msg\":\"Success\"}";
        }
    

    使用postman,我可以在其余部分看到相同的输入数据。但是当从NodeJS发送过来时,我看到的是

        { 
          timestamp: 1506987022646,
          status: 400,
          error: 'Bad Request',
          exception: 'org.springframework.http.converter.HttpMessageNotReadableException',
          message: 'Required request body is missing: public java.lang.String ApplicationController.startApp(java.lang.String)',
          path: '/start' 
        }
    

    在maven中使用spring boot starter父级。

    我这里有什么遗漏吗?如有任何建议,我们将不胜感激!

    1 回复  |  直到 7 年前
        1
  •  1
  •   LHCHIN    7 年前

    我不认为你把尸体放进去了 queryParams 将起作用。
    您可以尝试使用 req.write() 按如下方式将数据写入请求正文:

    ...  
    req.write(inputData);  
    req.end();
    ...