为什么我没有“访问控制允许来源”?

时间:2021-03-18 21:41:34

标签: c# asp.net .net api

我有用 vue.js 编写的前端和用 .net API 编写的后端。我尝试获取对象,但收到错误,我不知道发生了什么。 我的错误:

Access to XMLHttpRequest at 'http://localhost:50598/weatherforecast' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在控制器中的代码,在这里我设置了一个出现的断点。

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : Controller
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

}

和 vue js 脚本

<script>
import axios from 'axios'
const API_URL = 'http://localhost:50598/';
export default {
    name: "FetchData",
    data() {
        return {
            forecasts: []
        }
    },
    methods: {
        getWeatherForecasts() {
            axios.get(`${API_URL}weatherforecast`)
                .then((response) => {
                    this.forecasts =  response.data;
                })
                .catch(function (error) {
                    alert(error);
                });
        }
    },
    mounted() {
        this.getWeatherForecasts();
    }
}

如果我必须显示更多代码,那么写

1 个答案:

答案 0 :(得分:1)

信息很明确:

<块引用>

请求的资源上不存在“Access-Control-Allow-Origin”标头

因此,您正在执行跨源请求;即:从https://example1.com:someotherporthttps://example2.com:someport,由于缺少header而被浏览器屏蔽。

错误发生在:

  1. CORS 未配置
  2. CORS 已配置,但由于内部服务器错误等原因,未附加标头。

看看这个 MSDN 文档来解决它:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

相关问题