简体   繁体   中英

Why I get No 'Access-Control-Allow-Origin'?

I have front-end written in vue.js and back-end .net API. I trying get object but I receives error and I do not know what's going on. My error:

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.

My code in controller and here I set a breakpoint that comes out.

[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();
    }
}

}

and vue js script

<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();
    }
}

If I have to show more code then write

The message is clear:

No 'Access-Control-Allow-Origin' header is present on the requested resource

So, you are doing a cross origin request; ie: form https://example1.com:someotherport to https://example2.com:someport , and it is blocked by the browser due to the missing header.

The error occurs if:

  1. CORS is not configured
  2. CORS is configured, but due to an internal server error or such, the header is not appended.

Note: if you believe you did '1', most likely it's '2'

Have a look at this MSDN documentation to resolve it: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM