使用axios实现前后端交互:
1:安装axios模块,后面加上--save方便移动项目的时候也能使用模块
npm install axios --save
2:html代码定义按钮
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(Querys querys
public string Getvalue(string id, string name)
{
return "1111";
}
[Route("ToJson")]
[HttpGet]
public string ToJson(string id1, string name1)
{
List<people> peoples = new List<people>() {
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; }
}
public class Querys{
public string id { get; set; }
public string name { get; set; }
}
注意点:post后台和前台属性命名一一对应获取,不用对象获取的时候,参的参数应该放在第3个,也就是api路径后面必须加{},然后在是传的参数,不然后台获取为null
.post(api,{},{params:{id:'111',name:'222'}})//传值方式
public string Getvalue(string id, string name)//获取方式