req.body,req.query,req.params,req.param()取参数

本文介绍了Node.js的Express框架中获取请求参数的四种方法:req.body用于解析POST请求数据;req.query用于GET请求参数解析;req.params用于路由参数;req.param()已弃用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

nodejs的express框架为我们提供了四种方法来实现获取请求中的参数:

1.req.body
2.req.query
3.req.params
4.req.param()

1.req.body

通常用来解析POST请求中的数据
req.body不是nodejs默认提供的,需要载入中间件body-parser中间件才可以使用req.body
例如前台代码:

//jade模板
#signupModal.modal.fade
  .modal-dialog
    .modal-content
      form(method="POST",action="/user/signup")
        .modal-header 注册
        .modal-body
          .form-group
            label(for="signupName") 用户名
            input#signupName.form-control(name="user[name]",type="text")
          .form-group
            label(for="signupPassword") 密码
            input#signupPassword.form-control(name="user[password]",type="password")
        .modal-footer
          button.btn.btn-default(type="button",data-dismiss="modal") 关闭
          button.btn.btn-success(type="submit") 提交

后台代码:

var bodyParser = require('body-parser');
app.post('/user/signup',function (req,res) {
   var _user = req.body.user;
})
req.query

是由nodejs默认提供,无需载入中间件,此方法多适用于GET请求,解析GET请求中的参数
包含在路由中每个查询字符串参数属性的对象,如果没有则为{}
举例:

// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"
req.query.shoe.color
// => "blue"
req.query.shoe.type
// => "converse"
req.params

包含映射到指定的路线“参数”属性的对象

例如,如果你有route/user/:name,那么“name”属性可作为req.params.name。
nodejs默认提供,无需载入其他中间件

postget方式提交的表单的参数的获取,都可用req.params获取,但是需要注意的是:
假设现在我们以Post方式提交表单,在后台我们要获取到userid这个参数

我们提交的路径是/user/signup?1111userid=1122

这时如果我们通过req.params.userid获取到的并不是post表单提交上来的参数,这时因为req.params包含映射到指定的路线“参数”属性的对象,所以它在解析参数的时候包含URL中的路由,它获取的顺序是:
1.url中路由参数
2.post请求中提交参数
3.get请求中的参数
这里获取到的是1111,

如果提交的路径为:/user/signup?userid=1122
req.params.userid获取到的就是post提交的参数
req.param()

此方法被弃用,请看官方解释

Deprecated. Use either req.params, req.body or req.query, as applicable.
翻译:被弃用,用其他三种方式替换
package com.foonsu.efenxiao.platform.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.foonsu.efenxiao.biz.vo.FailOrder; import com.foonsu.efenxiao.common.enums.ShopPlatformClassType; import com.foonsu.efenxiao.common.enums.ShopPlatformType; import com.foonsu.efenxiao.common.exception.CommonErrorCode; import com.foonsu.efenxiao.common.exception.ServiceException; import com.foonsu.efenxiao.common.oss.OSSApiService; import com.foonsu.efenxiao.common.utils.CollectionsUtil; import com.foonsu.efenxiao.common.utils.ExceptionUtil; import com.foonsu.efenxiao.platform.dto.CidGoodsBatchUpdateDTO; import com.foonsu.efenxiao.platform.dto.SyncGoodsSearchDTO; import com.foonsu.efenxiao.platform.entity.PlatformGoods; import com.foonsu.efenxiao.platform.entity.PlatformGoodsSku; import com.foonsu.efenxiao.platform.entity.Shop; import com.foonsu.efenxiao.platform.handler.A1688GoodsLinkResolver; import com.foonsu.efenxiao.platform.handler.CidGoodsHandler; import com.foonsu.efenxiao.platform.platform.PlatformStarter; import com.foonsu.efenxiao.platform.service.IPlatformGoodsDistributeService; import com.foonsu.efenxiao.platform.service.IPlatformGoodsService; import com.foonsu.efenxiao.platform.service.IPlatformGoodsSkuService; import com.foonsu.efenxiao.platform.service.IShopService; import com.foonsu.efenxiao.platform.vo.*; import com.foonsu.efenxiao.system.dto.TenantDTO; import com.foonsu.efenxiao.user.feign.IFactorySellerRelClient; import com.foonsu.efenxiao.user.feign.IUserClient; import com.foonsu.efenxiao.user.feign.pdd.IPddFactorySellerRelClient; import com.foonsu.efenxiao.user.feign.pdd.IPddUserClient; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springblade.core.boot.ctrl.BladeController; import org.springblade.core.mp.support.Condition; import org.springblade.core.mp.support.Query; import org.springblade.core.secure.BladeUser; import org.springblade.core.secure.utils.AuthUtil; import org.springblade.core.tool.api.R; import org.springblade.core.tool.utils.CollectionUtil; import org.springblade.core.tool.utils.DateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.validation.Valid; import java.io.Serializable; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; /** * 控制器 * * @author BladeX * @since 2022-03-17 */ @Slf4j @RestController @RequestMapping("/platformgoods") @Api(value = "商品", tags = "商品") public class PlatformGoodsController extends BladeController { @Autowired private IPlatformGoodsService platformGoodsService; @Autowired private A1688GoodsLinkResolver a1688GoodsLinkResolver; @Autowired private IPlatformGoodsSkuService platformGoodsSkuService; @Autowired private IPlatformGoodsDistributeService platformGoodsDistributeService; @Autowired private PlatformStarter platformStarter; @Autowired private IShopService shopService; @Autowired private IFactorySellerRelClient factorySellerRelClient; @Autowired private ExceptionUtil exceptionUtil; @Autowired private IPddFactorySellerRelClient pddFactorySellerRelClient; @Value("${efenxiao.platformClass}") private ShopPlatformClassType platformClassType; @Autowired @Qualifier("goodsSyncThreadPoolTaskExecutor") private ThreadPoolTaskExecutor goodsSyncThreadPoolTaskExecutor; @Autowired private IUserClient userClient; @Resource private IPddUserClient pddUserClient; @Resource private CidGoodsHandler cidGoodsHandler; /** * 自定义分页 */ @GetMapping("/page") @ApiOperationSupport(order = 3) @ApiOperation(value = "分页(旧)", notes = "此接口需要删除,已经切换到pageNew") public R<IPage<PlatformGoodsVO>> page(PlatformGoodsReq req, Query query) { if(null == req || null == query){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } BladeUser user = AuthUtil.getUser(); req.setTenantId(user.getTenantId()); decorateReq(req); IPage<PlatformGoodsVO> pages = platformGoodsService.platformGoodsPage(Condition.getPage(query), req); return R.data(pages); } private void decorateReq(PlatformGoodsReq req){ if(StringUtils.isNotBlank(req.getProductOutIds())) { String productOutIdsStr = req.getProductOutIds().replaceAll(",", ","); String[] productOutIds = productOutIdsStr.split(","); req.setProductOutIdList(Arrays.asList(productOutIds)); } if(StringUtils.isNotBlank(req.getFactoryTenantId())) { String[] factoryTenantIds = req.getFactoryTenantId().split(","); req.setFactoryTenantIds(Arrays.asList(factoryTenantIds)); req.setFactoryTenantId(req.getFactoryTenantIds().get(0)); } if(StringUtils.isNotBlank(req.getSellerTenantId())) { String[] sellerTenantIds = req.getSellerTenantId().split(","); req.setSellerTenantIds(Arrays.asList(sellerTenantIds)); req.setSellerTenantId(req.getSellerTenantIds().get(0)); } if(StringUtils.isNotBlank(req.getShopBizId())) { String[] shopBizIds = req.getShopBizId().split(","); req.setShopBizIds(Arrays.asList(shopBizIds)); req.setShopBizId(null); } if (StringUtils.isNotBlank(req.getSkuOutIds())) { String[] skuOutIds = req.getSkuOutIds().split(","); req.setSkuOutIdList(Arrays.asList(skuOutIds)); req.setSkuOutIds(null); } } @GetMapping("/pageNew") @ApiOperationSupport(order = 3) @ApiOperation(value = "分页", notes = "传入platformGoodsReq") public R<IPage<PlatformGoodsVO>> pageNew(PlatformGoodsReq req, Query query) { if(null == req || null == query){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } BladeUser user = AuthUtil.getUser(); req.setTenantId(user.getTenantId()); decorateReq(req); IPage<PlatformGoodsVO> pages = platformGoodsService.platformGoodsPageNew(Condition.getPage(query), req, user); return R.data(pages); } /** * 同步商品 */ @PostMapping("/syncGoods") @ApiOperationSupport(order = 8) @ApiOperation(value = "同步商品", notes = "传入bizId") public R<List<GoodsSyncResp>> syncGoods(){ BladeUser user = AuthUtil.getUser(); List<String> tenantIds = ShopPlatformClassType.PDD == platformClassType? pddFactorySellerRelClient.queryAllParentTenantId(user.getTenantId()).getData(): factorySellerRelClient.queryAllParentTenantId(user.getTenantId()).getData(); List<Shop> shopListResult = shopService.getByTenantIds(tenantIds); R<List<TenantDTO>> tenantListR = platformClassType == ShopPlatformClassType.PDD ? pddUserClient.queryUserTags("cid") : userClient.queryUserTags("cid"); List<String> tenantIdList = tenantListR.getData().stream().map(TenantDTO::getTenantId).collect(Collectors.toList()); List<GoodsSyncResp> result = new ArrayList<>(); for (Shop shop : shopListResult) { GoodsSyncResp goodsSyncResp = new GoodsSyncResp(); if (ShopPlatformType.ZJ.getCode().equals(shop.getShopPlatform())) { continue; } if (shop.getAccessTokenTime().isBefore(LocalDateTime.now())) { goodsSyncResp.setSuccess(Boolean.FALSE); goodsSyncResp.setShopName(shop.getShopName()); goodsSyncResp.setErrorMsg("accessToken过期,请重新授权该店铺"); result.add(goodsSyncResp); shopListResult = shopListResult.stream().filter(shopInfo -> !shop.getBizId().equals(shopInfo.getBizId())).collect(Collectors.toList()); } } SyncGoodsParam syncGoodsParam = new SyncGoodsParam(); if (CollectionsUtil.isNotEmpty(tenantIdList)) { syncGoodsParam.setCidFlag(tenantIdList.contains(tenantIds.get(0))); } // 异步同步商品 platformStarter.asynGoods(shopListResult, syncGoodsParam); // List<Future<GoodsSyncResp>> futures = new ArrayList<>(); // for(Shop shop: shopListResult){ // Future<GoodsSyncResp> future = goodsSyncThreadPoolTaskExecutor.submit(()->{ // GoodsSyncResp res = platformStarter.syncGoods(shop, new SyncGoodsParam()); // return res; // }); // futures.add(future); // } // // for(Future<GoodsSyncResp> future: futures){ // try { // GoodsSyncResp res = future.get(); // log.info("GoodsSyncResp,{}", JSON.toJSONString(res)); // result.add(res); // } catch (Exception e) { // log.error("" ,e); // return R.fail(exceptionUtil.translateException(e)); // } // } return R.data(result); } /** * 修改商品简称或重量 */ @PostMapping("/updateGoodsAndSkuShotName") @ApiOperationSupport(order = 9) @ApiOperation(value = "修改商品简称或重量", notes = "传入platformGoodsVo") public R updateGoodsAndSkuShotName(@Valid @RequestBody PlatformGoodsUpdateReq req) { if (req == null || (req.getId() == null && CollectionsUtil.isEmpty(req.getSkuList()))) { throw new ServiceException(CommonErrorCode.PARAM_INVALID); } BladeUser user = AuthUtil.getUser(); List<PlatformGoodsUpdateReq> reqs = new ArrayList<>(); reqs.add(req); platformGoodsService.batchUpdateGoodsAndSkuShotName(user.getUserId(), reqs); return R.status(true); } /** * 批量修改商品简称或重量 * @param req 请求 * @return 返回 */ @PostMapping("/batchUpdateGoodsAndSkuShotName") @ApiOperationSupport(order = 9) @ApiOperation(value = "批量修改商品简称或重量", notes = "传入platformGoodsVo") public R<Boolean> batchUpdateGoodsAndSkuShotName(@Valid @RequestBody List<PlatformGoodsUpdateReq> req) { if (CollectionUtil.isEmpty(req)) { throw new ServiceException(CommonErrorCode.PARAM_INVALID); } BladeUser user = AuthUtil.getUser(); return R.status(platformGoodsService.batchUpdateGoodsAndSkuShotName(user.getUserId(), req)); } /** * 商品或规格批量绑定厂家 */ @PostMapping("/batchBindFactoryGoods") @ApiOperationSupport(order = 10) @ApiOperation(value = "商品或规格批量绑定厂家", notes = "传入goodsDistributeVOList") public R<Boolean> batchBindFactoryGoods(@Valid @RequestBody GoodsDistributeReq req) { if(null == req || CollectionsUtil.isEmpty(req.getDistributeList())){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } BladeUser user = AuthUtil.getUser(); //商品或规格批量绑定厂家 platformGoodsDistributeService.batchBindFactoryGoods(req, user); return R.status(true); } /** * 解绑对应厂家的商品关系 * @param req * @return */ @PostMapping("/unboundPlatformGoodsFactory") @ApiOperationSupport(order=11) @ApiOperation(value="解绑对应厂家的商品关系", notes = "distributeReq") public R<Boolean> unboundPlatformGoodsFactory(@RequestBody GoodsDistributeReq req) { if(null == req || CollectionsUtil.isEmpty(req.getDistributeList())){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } BladeUser user = AuthUtil.getUser(); platformGoodsDistributeService.unboundPlatformGoodsFactory(req.getDistributeList(), user); return R.status(true); } @GetMapping("/lastSyncTime") @ApiOperationSupport(order = 12) @ApiOperation(value = "获同步时间", notes = "") public R<Long> lastSyncTime() { BladeUser user = AuthUtil.getUser(); List<String> tenantIds = ShopPlatformClassType.PDD == platformClassType? pddFactorySellerRelClient.queryAllParentTenantId(user.getTenantId()).getData(): factorySellerRelClient.queryAllParentTenantId(user.getTenantId()).getData(); List<Shop> shopListResult = shopService.getByTenantIds(tenantIds); long time = shopListResult.stream().mapToLong(t->t.getGoodsSyncTime()==null?0L: DateUtil.toMilliseconds(t.getGoodsSyncTime())).max().orElseGet(()->0L); return R.data(time); } @PostMapping(value = "setDistributePrice") @ApiOperationSupport(order = 13) @ApiOperation(value = "设置分销价格", notes = "") public R<Boolean> setDistributePrice(@RequestBody GoodsDistributePriceReq req){ BladeUser user = AuthUtil.getUser(); return R.status(platformGoodsDistributeService.setDistributePrice(req,user)); } @PostMapping(value = "saveLocalGoods") @ApiOperationSupport(order = 14) @ApiOperation(value = "保存手工商品", notes = "") public R<Boolean> saveLocalGoods(@RequestBody LocalGoodsSaveReq req){ BladeUser user = AuthUtil.getUser(); checkParam(req); Set<String> usedImgs = new HashSet<>(); platformGoodsService.saveLocalGoods(user, req, usedImgs); userClient.uploadImgUsed(usedImgs, OSSApiService.goodsFolderName); return R.status(true); } @PostMapping(value = "batchSaveLocalGoods") @ApiOperationSupport(order = 18) @ApiOperation(value = "批量保存手工商品", notes = "") public R<List<FailOrder>> batchSaveLocalGoods(@RequestBody List<LocalGoodsSaveReq> reqs){ List<FailOrder> failOrders = new ArrayList<>(); for (LocalGoodsSaveReq req : reqs) { try{ this.saveLocalGoods(req); }catch (Exception e){ if (!(e instanceof Serializable)){ log.error("批量保存手工商品报错,{}" ,req.getProductName(), e); } FailOrder failOrder = new FailOrder(req.getProductName(), exceptionUtil.translateException(e)); failOrders.add(failOrder); } } return R.data(failOrders); } @PostMapping("/queryGoodsForSelect") @ApiOperationSupport(order = 15) @ApiOperation(value = "选择商品") public R<IPage<PlatformGoodsJoinSkuResp>> queryGoodsForSelect(@RequestBody LocalGoodsQueryReq req) { BladeUser user = AuthUtil.getUser(); IPage<PlatformGoodsJoinSkuResp> pages = platformGoodsService.queryGoodsForSelect(user, req); return R.data(pages); } @PostMapping("/deleteGoods") @ApiOperationSupport(order = 16) @ApiOperation(value = "删除手工商品") public R<Boolean> deleteGoods(@RequestBody LocalGoodsDeleteReq req) { BladeUser user = AuthUtil.getUser(); if (req.getGoodsBizIds() == null || req.getGoodsBizIds().size() == 0 ){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } if (req.getSkuBizIds() == null){ req.setSkuBizIds(new ArrayList<>()); } platformGoodsService.deleteGoods(req, user); return R.data(true); } private void checkParam(LocalGoodsSaveReq req) { if (StringUtils.isEmpty(req.getProductName()) || req.getShopBizId()==null){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } if (req.getSkus() != null && req.getSkus().size() > 0){ for (LocalGoodsSaveSkuReq sku : req.getSkus()) { if (StringUtils.isEmpty(sku.getSkuName())){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } } } } @PostMapping("/parseAlibabaGoodsLink") @ApiOperationSupport(order = 17) @ApiOperation(value = "解析阿里巴巴商品链接") public R<AlibabaResolveGoodsLinkResp> parseAlibabaGoodsLink(@RequestBody AlibabaResolveGoodsLinkReq req) { BladeUser user = AuthUtil.getUser(); if (StringUtils.isBlank(req.getLinkUrl()) ){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } AlibabaResolveGoodsLinkResp resp = a1688GoodsLinkResolver.parseAlibabaGoodsLink(user, req.getLinkUrl()); return R.data(resp); } @PostMapping("/bindAlibabaGoods") @ApiOperationSupport(order = 18) @ApiOperation(value = "绑定阿里巴巴商品") public R<Boolean> bindAlibabaGoods(@RequestBody AlibabaBindGoodsReq req) { BladeUser user = AuthUtil.getUser(); if (StringUtils.isBlank(req.getAlibabaProductId()) || StringUtils.isBlank(req.getFactoryTenantId()) || StringUtils.isBlank(req.getShopOauthId()) || req.getBindItems() == null || req.getBindItems().size() == 0 ){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } platformGoodsDistributeService.bindAlibabaGoods(user, req); return R.data(true); } @GetMapping("/getPlatformGoodsList") public R<List<LogisticsMatchPlatformGoodsVO>> getPlatformGoodsList(PlatformGoodsReq req) { BladeUser user = AuthUtil.getUser(); req.setTenantId(user.getTenantId()); req.setPageStart(1L); req.setPageSize(10000L); List<LogisticsMatchPlatformGoodsVO> platformGoodsVOS = platformGoodsService.queryPlatformGoodsByTenantId(req); return R.data(platformGoodsVOS); } @PostMapping("/getPlatformGoodsListByPage") @ResponseBody public R<Page<PlatformGoods>> getPlatformGoodsListByPage(@RequestBody SyncGoodsSearchDTO syncOrderGoodsDTO) { Page<PlatformGoods> platformGoodsPage = platformGoodsService.queryPlatformGoodsBySync(syncOrderGoodsDTO); return R.data(platformGoodsPage); } @PostMapping("/getPlatformGoodsSkuListByPage") @ResponseBody public R<Page<PlatformGoodsSku>> getPlatformGoodsSkuListByPage(@RequestBody SyncGoodsSearchDTO syncOrderGoodsDTO) { Page<PlatformGoodsSku> platformGoodsSkuPage = platformGoodsSkuService.queryPlatformGoodsSkuBySync(syncOrderGoodsDTO); return R.data(platformGoodsSkuPage); } @PostMapping("/batchUpdateCidGoodsInfo") @ResponseBody public R<Boolean> batchUpdateCidGoodsInfo(@RequestBody List<CidGoodsBatchUpdateDTO> cidGoodsBatchUpdateDTOS) { BladeUser user = AuthUtil.getUser(); Boolean aBoolean = platformGoodsService.batchUpdateCidGoodsInfo(user.getTenantId(), cidGoodsBatchUpdateDTOS); return R.data(aBoolean); } @GetMapping("/cidPage") @ApiOperationSupport(order = 3) @ApiOperation(value = "分页", notes = "传入platformGoodsReq") public R<IPage<PlatformGoodsVO>> cidPage(PlatformGoodsReq req, Query query) { if (null == req || null == query) { throw new ServiceException(CommonErrorCode.PARAM_INVALID); } BladeUser user = AuthUtil.getUser(); req.setTenantId(user.getTenantId()); decorateReq(req); IPage<PlatformGoodsVO> pages = platformGoodsService.platformGoodsPageByCid(Condition.getPage(query), req, user); return R.data(pages); } @PostMapping("/importCidGoodsFile") public R<Boolean> importCidGoodsFile(MultipartFile file) { BladeUser user = AuthUtil.getUser(); cidGoodsHandler.importCidGoods(file, user.getTenantId()); return R.success("导入成功"); } @PostMapping("/importCidOrderGoodsFile") public R<Boolean> importCidOrderGoodsFile(MultipartFile file) { BladeUser user = AuthUtil.getUser(); cidGoodsHandler.importCidOrderGoodsFile(file, user.getTenantId()); return R.success("导入成功"); } } 解释一下 我代码能力有点差
最新发布
07-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值