1、跨域问题参考
2、Html
@{ Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AxiosGet</title>
<link href="~/css/style.css" rel="stylesheet" />
<script src="/js/vue.min.js"></script>
<script src="~/js/axios.min.js"></script>
</head>
<body>
<div>
<br />
<div class="latest_fabric">
<ul>
<li id="example-1"><input type="button" value="GET请求1 初始化页面,加载数据" /><i>{{info}}</i></li>
<li id="example-2"><input type="button" value="GET请求2" v-on:click="getUser" /><i>{{info}}</i></li>
@*<li id="example-3"><input type="button" value="GET请求3 通过 params 对象传递参数" @@click="getUser" /><i>{{info}}</i></li>
<li id="example-4"><input type="button" value="GET请求4 通过 params 对象传递参数" v-on:click="getUser" /><i>{{info}}</i></li>*@
<li id="example-3"><button @@click="getUser">GET请求3 通过 params 对象传递参数</button><i>{{info}}</i></li>
<li id="example-4"><button v-on:click="getUser">GET请求4 通过 params 对象传递参数</button><i>{{info}}</i></li>
<li id="example-5"><button v-on:click="getUser">GET请求5 执行多个并发请求</button><i>{{info}}</i></li>
<li id="example-6"><button v-on:click="getUser">GET请求6 url参数请求</button><i>{{info}}</i></li>
<li id="example-7"><button v-on:click="getUser">GET请求7 url参数请求</button><i>{{info}}</i></li>
</ul>
</div>
<br />
</div>
<script>
axios.defaults.baseURL = "https://localhost:44390/api";
new Vue({
el: '#example-1',
data() {
return { info: null }
},
mounted() {
/* 初始化页面,加载数据 */
/* 不能使用this.asxios,报错 */
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(response => (this.info = response));
}
})
new Vue({
el: '#example-2',
data: { info: null },
methods: {
getUser: function () {
/* 不能使用this.asxios,报错 */
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then((response) => {
console.log(response);
this.info = response;
}).catch((error) => {
console.log(error)
})
}
}
})
new Vue({
el: '#example-3',
data: { info: null },
methods: {
getUser: function () {
/* 通过 params 对象传递参数 */
/* 不能使用this.asxios,报错 */
axios.get('/Default/GetAuthor', {
//headers: {
// 'host':'localhost:44390',
// 'content-type':'application/json'
// 'Authorization':'Bearer eyJhbGciOiJSUzI1N'
//},
params: { id: 1, alias: "liudehua" }
}).then((response) => {
// response.data中获取ResponseData实体
console.log(response.data);
this.info = response;
}).catch(function (error) {
// 发生错误
console.log("出错了:" + error)
});
}
}
})
new Vue({
el: '#example-4',
data: { info: null },
methods: {
getUser: function () {
/* 通过 params 对象传递参数 */
/* 不能使用this.asxios,报错 */
axios.get('/Default/Search', {
//headers: {
// 'host': 'localhost:44390',
// 'content-type':'application/x-www-form-urlencoded'
// 'Authorization':'Bearer eyJhbGciOiJSUzI1N'
//},
params: { namelike: "liudehua" }
}).then((response) => {
// response.data中获取ResponseData实体
console.log(response.data);
this.info = response;
}).catch(function (error) {
// 发生错误
console.log("出错了:" + error)
});
}
}
})
new Vue({
el: '#example-5',
data: { info: null },
methods: {
getUser: function () {
//执行多个并发请求
function getUserAccount() {
return axios.get('https://api.coindesk.com/v1/bpi/currentprice.json');
}
function getUserPermissions() {
return axios.get('https://api.coindesk.com/v1/bpi/currentprice.json');
}
axios.all([getUserAccount(), getUserPermissions()]).then(axios.spread(function (acct, perms) {
//两个请求现已完成
console.log("1:" + JSON.stringify(acct));
console.log("2:" + perms);
})).catch(function (error) {
console.log(error);
});
}
}
})
new Vue({
el: '#example-6',
data: { info: null },
methods: {
getUser: function () {
/* 不能使用this.asxios,报错 */
axios.get('/Default/Search?namelike=liudehua').then((response) => {
console.log(response.data);
this.info = response;
}).catch(function (error) {
// handle error
console.log(error);
});
}
}
})
new Vue({
el: '#example-7',
data: { info: null },
methods: {
getUser: function () {
// GET request for remote image
axios({
method: 'get',
url: '/Default/Search?namelike=liudehua',
}).then((response) => {
console.log(response.data);
this.info = response;
}).catch(function (error) {
// handle error
console.log(error);
});
}
}
})
</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; }
}
}