七、Axios入门
一、介绍当前最流行的一个前端请求框架,用于发送Ajax请求可以浏览器以及node中发送网络请求本文以node为例npm安装1. node客户端
·
一、介绍
- 当前最流行的一个前端请求框架,用于发送Ajax请求
- 可以浏览器以及node中发送网络请求
- 本文以node为例
- npm安装
1. axios
/*导入axios*/
const axios = require('axios').default;
/*返回的是一个Promise对象,获取结果*/
/*1. get无参*/
axios({
method: 'GET',
url: 'http://localhost:8080/erick/name',
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error.message);
})
/*2. get带参*/
axios({
method: 'GET',
url: 'http://localhost:8080/erick/nameWithArgs',
/*参数用params传递*/
params: {
id: 10,
brand: 'apple',
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error.message);
})
/*3 post无参*/
axios({
method: 'POST',
url: 'http://localhost:8080/erick/update',
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error.message);
})
/*4. post带参*/
axios({
method: 'POST',
url: 'http://localhost:8080/erick/updateWithArgs',
/*请求体用data表示, 对应后端是用@RequestBody来接受参数*/
data: {
name: 'erick',
age: 18,
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error.message);
})
package com.nike.erick.controller;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/erick")
public class AxiosController {
/*1. get不带参*/
@GetMapping("/name")
public String getName() {
return "Post Method without Args";
}
/*2. get带参*/
@GetMapping("/nameWithArgs")
public String getNameWithArgs(Integer id, String brand) {
return brand + id;
}
/*post不带参*/
@PostMapping("/update")
public String updateUser() {
return "Post Method without Args";
}
/*post不带参*/
@PostMapping("/updateWithArgs")
public Student updateUserWithArgs(@RequestBody Student student) {
return student;
}
}
更多推荐
所有评论(0)