I am new to Angular and I am trying to fetch data from webApi controller and displaying it on button click but, when I click on a button, I get error:
Access to XMLHttpRequest at 'http://localhost:5000/api/values' from origin 'https://localhost:5003' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is my WebApi Values Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace DataApi.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value3" };
}
}
}
This is my value.component.ts file:
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-value',
templateUrl: './value.component.html',
styleUrls: ['./value.component.css']
})
export class ValueComponent implements OnInit {
value = {};
constructor(private http: Http) { }
ngOnInit() {
}
getValues() {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
this.http.get(`http://localhost:5000/api/values`).subscribe ( response => this.value =
response.json());
}
}
This is my value.component.html:
<p>value works!</p>
<div>
<button (click)="getValues()">Load values</button>
{{ value | json }}
</div>
This is my app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ValueComponent } from './value/value.component';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
const appRoutes: Routes = [
{path: '', redirectTo: 'value', pathMatch: 'full' },
{ path: 'value', component: ValueComponent },
{ path: '**', redirectTo: ''}
];
@NgModule({
declarations: [
AppComponent,
ValueComponent
],
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
When I debug the project and click on the button, I get the error.
As I am new to Angular, I don't know what to do. When I click this URL: http://localhost:5000/api/values I get my values.