最近在项目中使用vue.js进行前端开发,刚刚接触vue一路磕磕绊绊遇到了很多问题,在这里记录下解决办法。

 这是我们系统中前端的一个axios发送http请求的部分代码片段,向后台发送http请求,后端springBoot始终接收不到

@RequestParam的参数,看下面:

// 封装axios
const http =axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// 发送post请求
this.$http({
    url: 'http://localhost:8080/bindT/1'),
    method: 'post',
    data: {
        ids : ['1','2','3']
    }
}).then(({data}) => {
    if (data && data.code === 0) {
        this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500
        })
    } else {
        this.$message.error(data.msg)
    }
})
@RequestMapping("/bindT/{type}")
public R bindT(@PathVariable("type") String type, @RequestParam List<String> ids) {
    System.out.println("ids:" + ids.toString());
    return R.ok();
}
2020-07-09 15:15:10.422 ERROR 13316 --- [io-8097-exec-24] c.b.s.c.exception.RRExceptionHandler : 
Required List parameter 'ids' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required List parameter 'ids' is not present
	at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)
	at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:112)
	at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:124)

在网上也找了好多办法都没有解决,如:修改data里面的内容使用dataForm封装、修改headers等等。最终找到一个解决办法:修改headers信息使用

'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'

并且对参数进行

 URLSearchParams()

封装处理。

效果参考下面:

// 封装axios
const http =axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// 对参数进行封装
let searchParams = new URLSearchParams()
searchParams.set('ids', ['1','2','3'])

//发送post请求
this.$http({
    url: 'http://localhost:8080/bindT/1'),
    headers: { //修改头信息,因为只有该处使用,所以不修改全局配置
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
    },
    method: 'post',
    data: searchParams
}).then(({data}) => {
    if (data && data.code === 0) {
        this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500
        })
    } else {
        this.$message.error(data.msg)
    }
})

 后端就可以正常接收了

ids:[1,2,3]
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐