(十二)axios实现前后端交互(post,get请求传参,URLSearchParams传参)
使用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)//获取方式
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!