Axios通过传统方式使用GET和POST

这里介绍的是Axios使用传统的方式引入依赖,通过CDN或者引入JS文件的方式,下面分别就GET好POST方式来处理

  <div class="welcomebox" id="app">
        <p id="hero"></p>
        <button @click="postAxios()">postAxios</button>
  </div>

引入CDN依赖,这里面引入俩个模块,其中QS是用来处理传递的参数的,因为Axios默认是以JSON格式传输的,而我后端是使用@RequestParam来接收的,当然如果你使用@RequestBody来接收那么就不需要了

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcss.com/qs/6.5.1/qs.min.js"></script>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                info: null
            }
        },
        methods: {
            //POST方式
            postAxios: function () {
                var headers = {};
                headers['X-CSRF-TOKEN'] = "[[${_csrf.token}]]";
                axios({
                    method: 'post',
                    url: '/admin/rest/demo/show',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRF-TOKEN': "[[${_csrf.token}]]"
                    },
                    data: Qs.stringify({'apptype': 'APPTYPE001'})
                }).then(function (response) {
                    var jsonObject = response.data;
                    var jsonString = JSON.stringify(jsonObject)
                    document.getElementById("hero").innerHTML = "通过 axios 获取到的json数据:" + jsonString;
                }).catch(function (error) {
                    console.log(error);
                });


            }
        },
        mounted() {
            //GET方式
            axios
                .get('/admin/rest/demo/show')
                .then(function (response) {
                    var jsonObject = response.data;
                    var jsonString = JSON.stringify(jsonObject)
                    document.getElementById("hero").innerHTML = "通过 axios 获取到的json数据:" + jsonString;
                }).catch(function (error) { // 请求失败处理
                console.log(error);
            });
        }
    })
</script>

后端代码

@Slf4j
@RestController
@RequestMapping("/admin/rest/demo")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Demo {

    private final SystDictService systDictService;

    @GetMapping("/show")
    public ApiResponse show() {
        List<SystDict> systDicts = systDictService.listSystDictCenter();
        return ApiResponse.ofSuccess(systDicts);
    }

    @PostMapping("/show")
    public ApiResponse show(@RequestParam( "apptype") String apptype) {
        SystDict systDictByName = systDictService.getSystDictByName(apptype);
        return ApiResponse.ofSuccess(systDictByName);
    }
}

你可能感兴趣的:(前端)