Get和Post请求前后端交互易错的地方

Get和Post请求前后端交互易错的地方

首先说下get和post的区别:

  1. get请求时通过URL直接请求数据,数据信息可以在URL中直接看到,比如浏览器访问;而post请求是放在请求头中的,用户无法直接看到。
  2. get是从服务器上获取数据,post是向服务器传送数据。

(3)get传送的数据量有限制,不能大于2KB;这主要是因为它受约于URL长度的限制,而POST没有。

(4)GET比POST更不安全,因为参数直接暴露在URL上,所以不能用来传递敏感信息,比如密码。 

1.Get请求

@RequestParam 来接收参数

@GetMapping("/table/list")
public JsonData getList(@RequestParam Integer id){
  }

前端的请求:

export function getList(params) {

  return request({

    url: '/table/list',

    method: 'get',

    params

  })

}

apipost测试结果:

restful风格

@GetMapping("/table/list/{id}")
public JsonData getList2(@PathVariable Integer id){

前端请求:

export function getList(id) {

  return request({

    url: '/table/list/${id}',

    method: 'get'

  })

}

ApiPost请求

 

2. Post请求

@RequestParam 来接收参数

@RequestMapping("/fileUpload")
public JsonData uploadFile(@RequestParam("file") String  file,@RequestParam("user") String user)

前端请求:

export function login(data) {

  return request({

    url: '/fileUpload',

    method: 'post',

    data

  })

}

注意的是Content-Type要设置为application/x-www-form-urlencoded

Apipost请求:

 

@RequestBody接收参数

注意:

  1. @RequestBody接收的参数是来自requestBody中,即请求体。一般用于处理非 Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。
  2. GET请求中@RequestBody并不适用。
  3. @RequestBody 与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。
  4. 使用@RequestBody 时必须在方法上面加上@ResponseBody,如果没有加@ResponseBody,底层会将方法的返回值封装为ModelAndView对象。并返回视图。或者在类的上面加上@RestController

 相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了


@PostMapping("/saveContact")
public JsonData insert(@RequestBody Contact contact){

前端:

 saveContact(contact){

       return request({

        url: `/saveContact`,

        method: 'post',

        data: contact

       })

 }

Apipost请求:

 

restful风格


@PostMapping("/getContactList/{page}/{limit}")
public JsonData getAllInfo(@PathVariable("page") Integer p,@PathVariable("limit") Integer limit,
                           @RequestBody  ContactVO contactVO){

前端

getContactList(page,limit,searchObj){

        return request({

            url: `/getContactList/${page}/${limit}`,

            method: 'post',

            data: searchObj

        })

    }

总结:

(1)在交互中要注意Content-Type的设置

(2)前端的params和data

  params是添加到url的请求字符串中的,用于get请求。 服务器并不会读取http body里面的数据,这样我们传递的就是Params里的请求的参数了。

data是添加到请求体(body)中的, 用于post请求。服务器读取http body里面的数据那就需要用POST请求了,POST请求的参数就存放在body

(3)@RequestParam可以用来接收GET和POST的默认application/x-www-form-urlencoded格式的请求数据
@RequestBody只能接收POST的application/json格式的请求数据

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值