Vue axios HTTP POST请求

1、跨域问题参考

ASP.NET Core 启用跨域请求 (CORS)
vue-axios 安装
axios api
*
*

2、Html

@{ Layout = null;}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AxiosIndex</title>
    <link href="~/css/style.css" rel="stylesheet" />
    <script src="/js/vue.min.js"></script>
    <script src="~/js/axios.min.js"></script>
    <script src="~/js/qs/dist/qs.js"></script>
    @*<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>*@
</head>
<body>
    <div>
        <br />
        <div class="latest_fabric">
            <ul>
                <li id="example-1"><input type="button" value="POST 登陆" v-on:click="login" /><i>{{info}}</i></li>
                <li id="example-2"><input type="button" value="POST 注册" v-on:click="login" /><i>{{info}}</i></li>
                <li id="example-3"><input type="button" value="POST请求3" v-on:click="login" /><i>{{info}}</i></li>
                <li id="example-4"><input type="button" value="POST请求4" v-on:click="login" /><i>{{info}}</i></li>
                <li id="example-5"><button v-on:click="login">POST请求5</button><i>{{info}}</i></li>
                <li id="example-6"><button v-on:click="login">POST请求6</button><i>{{info}}</i></li>
                <li id="example-7"><button v-on:click="login">POST请求7</button><i>{{info}}</i></li>
                <li id="example-8"><button v-on:click="login">POST请求8</button><i>{{info}}</i></li>
            </ul>
        </div>
        <br />
    </div>
    <script>
        axios.defaults.baseURL = "https://localhost:44390/api";
        //axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
        //axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        //请求拦截
        axios.interceptors.request.use(
            (config) => {
                localStorage.setItem("token", "abcd");
                let token = localStorage.getItem("token");

                //在发送请求之前做某件事
                if (config.method.toLowerCase() === 'post') {
                }
                if (config.method.toLowerCase() === 'get') {
                    config.headers.Authorization = "Bearer " + token;
                    console.log("123");
                }
                return config;
            }, (error) => {
                console.log('错误的传参')
                return Promise.reject(error);
            }
        );

        //响应拦截
        axios.interceptors.response.use(
            response => {
                return response;
            },
            error => {
                if (error.response) {
                    switch (error.response.code) {
                        case 401:
                            // 返回 401 (未授权) 清除 token 并跳转到登录页面
                            break;
                        default:
                            break;
                    }
                }
                return Promise.reject(error.response.data) // 返回接口返回的错误信息
            }
        );
        new Vue({
            el: '#example-1',
            data: { info: null },
            methods: {
                login: function () {
                    let data = { Id: 1, Name: "abcd", Age: '25' }
                    axios.post('/Default/Login', data).then((response) => {
                        // response.data中获取ResponseData实体
                        console.log(response)
                        this.info = response;
                    }).catch(function (error) {
                        // 发生错误
                        console.log(error)
                    });
                }
            }
        })
        new Vue({
            el: '#example-2',
            data: { info: null },
            methods: {
                login: function () {
                    axios.post('/Default/LoginUrlEncoded', { Id: 1, Name: "abcd", Age: '25' }).then((response) => {
                        console.log(response);
                        this.info = response;
                    }).catch(function (error) {
                        console.log(error);
                    });
                }
            }
        })
        new Vue({
            el: '#example-3',
            data: { info: null },
            methods: {
                login: function () {
                    axios({
                        method: 'post',
                        url: "/Default/Login",
                        data: { Id: 1, Name: "abcd", Age: '25' }
                    }).then((response) => {
                        console.log(response);
                        this.info = response;
                    }).catch(function (error) {
                        console.log(error);
                    });
                }
            }
        })
        new Vue({
            el: '#example-4',
            data: { info: null },
            methods: {
                login: function () {
                    // Send a POST request
                    axios({
                        method: 'post',
                        url: '/Default/LoginUrlEncoded',
                        headers: {
                            'Content-type': 'application/x-www-form-urlencoded'
                        },
                        data: {
                            Id: 1,
                            Name: "abcd",
                            Age: '25'
                        },
                        transformRequest: [function (data) {
                            let ret = ''
                            for (let it in data) {
                                ret += it + '=' + data[it] + '&'
                            }
                            console.log(ret);
                            return ret
                        }],
                    }).then((res) => {
                        console.log(res)
                        this.info = res;
                    }).catch(function (error) {
                        console.log(error);
                    });
                }
            }
        })
        new Vue({
            el: '#example-5',
            data: { info: null },
            methods: {
                login: function () {
                    this.info = 'Hello World!';
                }
            }
        })
        new Vue({
            el: '#example-6',
            data: { info: null },
            methods: {
                login: function () {
                    this.info = 'Hello World!';
                }
            }
        });
        new Vue({
            el: '#example-7',
            data: { info: null },
            methods: {
                login: function () {
                    this.info = 'Hello World!';
                }
            }
        })
        new Vue({
            el: '#example-8',
            data: { info: null },
            methods: {
                login: function () {
                    this.info = 'Hello World!';
                }
            }
        })
    </script>
</body>
</html>

3、Controller(.NET Core API 服务端)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace Web.Api.Controllers
{
    [EnableCors("AllowSpecificOrigin")]
    [Route("api/[controller]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        // GET: api/Default
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/Default/alias
        [HttpGet("{alias}")]
        public Author Get(string alias)
        {
            return new Author { Id = 1, Name = alias, Age = 20 };
        }

        // GET api/Default/GetAuthor?id=100&alias=abc
        [HttpGet("GetAuthor")]
        public Author GetAuthor(int id, string alias)
        {
            return new Author { Id = id, Name = alias, Age = 20 };
        }

        // GET: api/Default/search?namelike=th
        [HttpGet("Search")]
        public IActionResult Search(string namelike)
        {
            var result = "result:" + namelike;
            if (!result.Any())
            {
                return NotFound(namelike);
            }
            return Ok(result);
        }

        // GET api/Default/about
        [HttpGet("About")]
        public ContentResult About()
        {
            return Content("An API listing authors of docs.asp.net.");
        }

        // GET api/Default/version
        [HttpGet("version")]
        public string Version()
        {
            return "Version 1.0.0";
        }

        // POST: api/Default
        [HttpPost]
        public void Post([FromBody] string value)
        {
            string dt = DateTime.Now.ToShortDateString();
        }

        [HttpPost("Login")]
        public IActionResult Login(Author data)
        {
            var result = $"result:{data.Id},{data.Name},{data.Age},{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
            return Ok(result);
        }

        [HttpPost("LoginUrlEncoded")]
        public IActionResult LoginUrlEncoded(int Id, string Name, int Age)
        {
            var result = $"result:{Id}{Name}{Age},{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
            return Ok(result);
        }

        [HttpPost("CreateCity")]
        public async Task<IActionResult> CreateCity(int countryId, Author data)
        {
            var result = $"result:{data.Id},{data.Name},{data.Age},{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
            return Ok(result);
        }

        [HttpPost("Add")]
        public bool Add(Author m)
        {
            try
            {
                var dt = DateTime.Now;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        // PUT: api/Default/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE: api/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }

    public class Author
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值