欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue axios HTTP POST请求

程序员文章站 2022-07-02 16:54:51
...

1、跨域问题参考

ASP.NET Core 启用跨域请求 (CORS)

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>
</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';
        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; }
    }
}

 

 

上一篇: IOS之tabBar

下一篇: axios的使用.md