最近在做一个前后端分离的示例,以下代码完美解决跨域的问题
一、后端服务
1.首先我们建一个.net core webapi的项目
2.项目引用Microsoft.AspNetCore.Cors 包
3.添加cors 服务
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //添加cors 服务 services.AddCors(options =>//p.WithOrigins这里就是配置策略,允许访问的地址
options.AddPolicy("Admin", p => p.WithOrigins("http://localhost:5000", "http://localhost:9528").AllowAnyMethod().AllowAnyHeader().AllowCredentials()) ); }
4.配置Cors
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } //配置Cors app.UseCors("Admin"); app.UseHttpsRedirection(); app.UseMvc(); }
5.编写控制器
[Route("api/[controller]")] [ApiController] public class GetDataController : ControllerBase { // GET api/values [HttpGet] [EnableCors("Admin")] public ActionResult<IEnumerable<string>> Get() { return new string[] { DateTime.Now.ToString() }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } }
二、前段
1.创建Vue前段项目,我这里是使用的是vue+element (自己百度创建)
2.安装axios模块 npm install axios -g
3.调用api
export default {
data() {
return {
msg:''
}
},
methods: {
onSubmit() {
let _self=this;
console.log(this.form)
axios.get('http://localhost:5000/api/GetData')
.then(function (response) {
console.log(response);
_self.msg=response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
}