react中axios结合后端实现GET和POST请求

区别在这里不做介绍了,POST方法比GET方法稍微安全一点,GET方法比POST方法要快一些,个人感觉传递单个参数用GET,传递多个参数用POST。

get实现方式1(参数直接在url中)

前端

export function getAllSubstationsByUser() {
    
    
  return axios.get(`/api/integratedEnergy/all/${
      
      user}/substations`);
}

后端

   @RequestMapping(value = "/all/{user}/all/substations", method = RequestMethod.GET)
    public  ResponseEntity<List<Map<String, Object>>> getAllSubstationsByUserAreas(@PathVariable("user") String user) {
    
    
    String a = user;
    // todo 实现方法
}

get时间方式2(作为JSONString跟在url末尾)

前端

  const params = {
    
    
      user: 'admin',
    };
    
export function getAllSubstationsByUser(params) {
    
    
  return axios.get(`/api/integratedEnergy/all/substations`, {
    
     params });
}

后端

    @RequestMapping(value = "/all/substations", method = RequestMethod.GET)
    public ResponseEntity<List<Map<String, Object>>> getAllSubstationsByUserAreas(@RequestParam(value = "user", defaultValue = "") String user) {
    
    
        List<Map<String, Object>> mapList = new ArrayList<>();
        String a = user;
        // todo 实现方法
        return new ResponseEntity<>(mapList, HttpStatus.OK);
    }

post实现(传递JSONObject)

前端

const params = {
    
     id: 'admin', name: '用户' }

export function getChildrenDevicesByParent(params) {
    
    
  return axios.post(`/api/integratedEnergy/all/child/devices`, params);
}

后端

   @RequestMapping(value = "/all/child/devices", method = RequestMethod.POST)
    public ResponseEntity<List<Map<String, Object>>> getStorageHistoryData(@RequestBody JSONObject params) {
    
    
    List<Map<String, Object>> mapList = new ArrayList<>();
	String id = params.getString("id").trim());
	String name = params.getString("name").trim());
	// todo 实现方法

    return new ResponseEntity<>(mapList, HttpStatus.OK);
    }

猜你喜欢

转载自blog.csdn.net/qq_34307801/article/details/105046975