(十二)axios实现前后端交互原理以及选择axios做交互的原因 (初级篇)
选择axios原因和历史背景:
vue-source是vue自带得前后的交互得模块,但是后来因为axios得功能越来越强大了,所以vue也没有在单独在去做vue-source得深入开发,后面已经放弃维护,后面vue官网也推荐使用axios,
axios是一个单独得插件,不是专门为vue服务得,rect.js一样也能使用axios,因为vue-source已经放弃了后面得维护,和功能远不如axios强大,所以vue-source基本可以忽略
使用axios实现前后端交互:
1:安装axios模块,后面加上--save方便移动项目的时候也能使用模块
npm install axios --save
2:html代码定义按钮
- {{item.name}}--{{item.no}}
1:ConfigureServices里面配置跨域
string corsUrls = "http://192.168.2.117:8081,http://192.168.2.117:8080,http://192.168.2.117:8082,http://192.168.2.117:8083";
if (string.IsNullOrEmpty(corsUrls))
{
throw new Exception("请配置跨请求的前端Url");
}
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins(corsUrls.Split(",")).AllowCredentials()
.AllowAnyHeader().AllowAnyMethod();
});
});
2:Configure里面启用跨域
app.UseCors();//启用跨域,启用跨域写在UseAuthorization上面
app.UseAuthorization();
[Route("/api/Test")]
[ApiController]
public class TestController : ControllerBase
{
[Route("Getvalue")]
[HttpPost]
public string Getvalue()
{
return "1111";
}
[Route("Getvalueget")]
[HttpGet]
public string Getvalueget()
{
return "222";
}
[Route("ToJson")]
[HttpGet]
public string ToJson()
{
List
new people() { name="zhangsan",no="111"} ,
new people() { name="李四",no = "222" }
};
string ListJson = JsonConvert.SerializeObject(peoples);
return ListJson;
}
}
public class people
{
public string name { get; set; }
public string no { get; set; }
}