一、介绍

  • 当前最流行的一个前端请求框架,用于发送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;
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐