.Net6 web API (跨域请求 Vue项目)

前沿

在做新项目的时候

跨域2中选择 一种是,.net 

.net 

        //添加跨域策略
        builder.Services.AddCors(options => {
            options.AddPolicy("CorsPolicy", opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("X-Pagination"));
         });
        //使用跨域策略/
        app.UseCors("CorsPolicy");

 

创建

Controllers
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using yanfanNet6WebApi;

namespace fanfanFlower.WebAPI.Controllers
{
    //[Route("api/[controller]/[action]")]
    [Route("[controller]/[action]")]
    [ApiController]
    //[ApiVersion("2.0")]
    //[Route("[controller]/v{version:apiVersion}")]
    public class ImageController : ControllerBase
    {
        [HttpGet]
        public List<ImageModel> GetImages()
        {
            return new List<ImageModel>() {
                new ImageModel(){ ImageUrl="/images/banners/21_birthday_banner_pc.jpg", CourseUrl="http://localhost:5173/" },
                new ImageModel(){ ImageUrl="/images/banners/21_brand_banner_pc.jpg",CourseUrl="http://localhost:5173/" },
                new ImageModel(){ ImageUrl="/images/banners/21_syz_banner_pc.jpg",CourseUrl="http://localhost:5173/" },
           // "/images/banners/21_birthday_banner_pc.jpg","/images/banners/21_brand_banner_pc.jpg","/images/banners/21_syz_banner_pc.jpg"
            };
        }
    }
}

 

imageModel.cs

namespace yanfanNet6WebApi
{
    public class ImageModel
    {
        
      public string ImageUrl { get; set; }

      public string CourseUrl { get; set; }
    }
}

 

 

介入vue请求数据

vue项目 

server: {
  proxy: {
    '/api': { // 获取请求中带 /api 的请求
      target: 'http://localhost:8080',  // 后台服务器的源
      changeOrigin: true,   // 修改源
      rewrite: (path) => path.replace(/^\/api/, "")   //  /api 替换为空字符串
    },
    headers: {
      "Origin-Agent-Cluster": "?0"
    },
  }
}

然后页面请求

 

import axios from 'axios'; 
import { ref } from 'vue';
const http = ref('http://localhost:5206/api');
//获取首页Banner轮播图
export const getBanners2 = () => {
    return axios.get(http.value + '/Image/GetImages');
}

 

OK  完美

posted @ 2024-05-21 18:03  -鹿-  阅读(30)  评论(0编辑  收藏  举报