NodeJS中如何向http.request传递变量并在后端POST接口获取?
在NodeJS POST请求中传递
isParentSenior并在JAX-RS接口中获取 下面提供两种可行的实现方式,根据业务场景选择:
方案1:通过请求体传递(推荐)
POST请求的参数通常放在请求体中,符合REST接口的设计规范。
NodeJS侧修改
构造包含isParentSenior的JSON请求体,并正确设置请求头的Content-Length:
var URL = 'parent/test'; var isParentSenior = true; var output = ''; // 构造请求体JSON var input = JSON.stringify({ isParentSenior: isParentSenior }); var options = { host: config.ip, path: config.rest_prefix + URL, method: 'POST', rejectUnauthorized: false, headers: { 'Authorization': token, 'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': Buffer.byteLength(input, 'utf8'), 'Browser': userUtil.detectBrowserNameAndVersion(req.headers['user-agent']), 'ip_address': req.headers['x-forwarded-for'] } }; var reqPost = https.request(options, function (resPost) { resPost.on('data', function (d) { output = output + d; }); resPost.on('end', function () { logger.info('Final POST result***:\n' + output); }); }); // 写入请求体 reqPost.write(input); reqPost.end();
JAX-RS后端获取
可以通过自定义实体类接收请求体,或者直接用Map解析:
方式A:自定义实体类
// 定义请求实体类 public class ParentRequest { private boolean isParentSenior; // JAX-RS需要无参构造器 public ParentRequest() {} // Getter和Setter public boolean isParentSenior() { return isParentSenior; } public void setIsParentSenior(boolean isParentSenior) { this.isParentSenior = isParentSenior; } } // 修改接口方法 @POST @Path("parent/test") @Consumes(MediaType.APPLICATION_JSON) public Response addParent(ParentRequest requestBody){ boolean isParentSenior = requestBody.isParentSenior(); // 后续业务逻辑处理 return Response.ok().build(); }
方式B:用Map接收(快速调试场景)
@POST @Path("parent/test") @Consumes(MediaType.APPLICATION_JSON) public Response addParent(Map<String, Object> requestBody){ Boolean isParentSenior = (Boolean) requestBody.get("isParentSenior"); // 后续业务逻辑处理 return Response.ok().build(); }
方案2:通过请求头传递
如果参数属于元数据范畴,可以放在请求头中传递:
NodeJS侧修改
在options.headers中新增自定义请求头字段:
var options = { host: config.ip, path: config.rest_prefix + URL, method: 'POST', rejectUnauthorized: false, headers: { 'Authorization': token, 'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': Buffer.byteLength(input, 'utf8'), 'Browser': userUtil.detectBrowserNameAndVersion(req.headers['user-agent']), 'ip_address': req.headers['x-forwarded-for'], // 新增自定义请求头传递参数 'X-Is-Parent-Senior': isParentSenior.toString() } }; // 若原本无请求体,需移除Content-Length或设置为0
JAX-RS后端获取
通过HttpServletRequest获取请求头:
@POST @Path("parent/test") public Response addParent(@Context HttpServletRequest request){ String isParentSeniorStr = request.getHeader("X-Is-Parent-Senior"); boolean isParentSenior = Boolean.parseBoolean(isParentSeniorStr); // 后续业务逻辑处理 return Response.ok().build(); }
内容的提问来源于stack exchange,提问作者mosid
相关产品推荐
相关产品推荐

