NetCore跨域的實現

1.安裝程序CORS程序包

使用npm來安裝包:Microsoft.AspNetCore.Mvc.Cors

2.配置CORS服務

在 Startup類,ConfigureServices方法裏,添加如下代碼:
services.AddCors(option=>option.AddPolicy("策略名稱", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().AllowAnyOrigin()));

新版的CORS中間件已經阻止使用允許任意Origin,即 AllowAnyOrigin 設置了也不會生效,詳情如下:

解決辦法:使用 WithOrigins 來設置 Origin

policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(new []{"http://xxx.xxx.com"});

 

在 Startup類,Configure方法裏,添加如下代碼:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseCors("策略名稱");
    app.UseMvc();
}

其他寫法:

當然也可以不在ConfigureServices裏面建策略,我在ConfigureServices中直接添加代碼:

services.AddCors();

我在Configure中添加代碼:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder.WithOrigins("http://localhost:8080"));//添加這行
app.UseRouting();
app.UseAuthorization();

3、後臺之前寫版本控制的時候已經寫過了,看下VUE前端。

<script>
  export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: '這是HelloWorld.Vue APP地址!',
      a:0,
      b:1,
      c:3
      }
    },
    methods: {
      changeData(){
        this.a = 10,
          this.b = 20,
          this.c = 30
      }
    },
    mounted() {
      getData0416:{
        let url = 'api/v2/vt02/666666';
        this.$axios.get(url, { id: "88888888" })
          .then(res => {
            console.log(res);
            this.list = res.data;// 將獲取回來的數據賦值給list
            console.log(this.list);
            this.msg = this.msg + this.list.ms + this.list.dd;
          })
          .catch(err => {
            console.log(err);
          })
      }
    }
}
</script>

成功獲取值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章