Post请求传参(表单传值)
<script>
post4()
function post4(){
let id=12;
let name="找死";
fetch("api/show", {
method:"post",
headers:{'content-type':'application/x-www-form-urlencoded;charset=utf-8'},
body:`id=${id}&name=${name}`
}).then(res=>res.json()).then(res=>{
console.log("服务端返回的值")
console.log(res)
}).catch(err=>{
console.log("catch........")
console.log(err)
})
}
</script>
后端接收值
//Dog类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dog {
private Integer id;
private String name;
}
//配置类
@RequestMapping("/api/show")
@ResponseBody
public Map<String, Object> show( Dog dog, HttpServletRequest req){
Map<String, Object> map=new HashMap<>();
map.put("code",200);
map.put("message",req.getMethod());
map.put("ip",req.getRemoteAddr());
map.put("data",dog);
return map;
}
普通的Get请求传参
function get2(){
fetch('api/show?id=11&name=张三',{
method: 'GET'
}).then(res=>res.text()).then(res=>{
console.log(res)
}).catch(err=>{
console.log("catch........")
console.log(err)
})
}
后端接收值
@RequestMapping("/api/show")
@ResponseBody
public Map<String, Object> show( Dog dog, HttpServletRequest req){
Map<String, Object> map=new HashMap<>();
map.put("code",200);
map.put("message",req.getMethod());
map.put("ip",req.getRemoteAddr());
map.put("data",dog);
return map;
}
Post请求负载
post5()
function post5(){
let id=12;
let name="造势"
fetch("api/show", {
method: "POST",
headers:{'content-type':'application/json;charset=utf-8'},
body: JSON.stringify({id,name})
}).then(res=>res.json()).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
后端接收值
@RequestMapping("/api/show")
@ResponseBody
public Map<String, Object> show( @RequestBody Dog dog, HttpServletRequest req){
Map<String, Object> map=new HashMap<>();
map.put("code",200);
map.put("message",req.getMethod());
map.put("ip",req.getRemoteAddr());
map.put("data",dog);
return map;
}