Vue——通过axios跨域访问

html页面
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div id="app">
    <ul>
        <li>姓名:{{user.username}}</li>
    </ul>

</div>

<!-- 生产环境版本,优化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!--引入Axios-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        data() {
            return {
                user: {
                    username: ""
                }
            }
        },
        mounted() {
            axios.get("http://localhost:8080/user")
                .then(response => this.user = response.data)
        }
    });
</script>
</body>
</html>
js文件
var Utils = function () {
    var username;

    var setUsername = function (username) {
        this.username = username;
    }

    var getUsername = function () {
        return this.username;
    }

    return {
        setUsername: function (username) {
            setUsername(username);
        },

        getUsername: function () {
            return getUsername();
        }
    }
}();
// 表示函数对象
Springboot项目领域对象
package com.xiaobai.springboot.axios.domain;

import java.io.Serializable;

public class User implements Serializable {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Controller类——@CrossOrigin("*") 要加这个注解才能跨域!!!
package com.xiaobai.springboot.axios.controller;

import com.xiaobai.springboot.axios.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@CrossOrigin("*")
@Controller
@ResponseBody
public class UserController {

    @GetMapping(value = "/user")
    public User user(){
        User user = new User();
        user.setUsername("王二");

        return user;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值