I have been spending hours and hours about looking a way to enable my front end web app (Angular) to access my Asp.NET MVC (Controller) but it displays the following error:
http://localhost:49603/api/datapaths 500 (Internal Server Error)
Access to XMLHttpRequest at 'http://localhost:49603/api/datapaths' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:49603/api/datapaths", ok: false, …}
proxy.conf.json:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
Package.json:
Start line has been changed
"start": "ng serve --proxy-config proxy.conf.json",
empolyee.service:
import { Injectable } from '@angular/core';
import { Empolyee } from './empolyee.model';
import{HttpClient} from '@angular/common/http'
@Injectable({
providedIn: 'root'
})
export class EmpolyeeService {
formData: Empolyee;
constructor(private http:HttpClient) { }
postEmpdata(formData: Empolyee){
return this.http.post("http://localhost:49603/api/datapaths",formData);
}
}
empdata.component.ts:
import { Component, OnInit } from '@angular/core';
import { EmpolyeeService } from 'src/app/shared/empolyee.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-empdata',
templateUrl: './empdata.component.html',
styleUrls: ['./empdata.component.css']
})
export class EmpdataComponent implements OnInit {
constructor(private service:EmpolyeeService) { }
ngOnInit() {
this.resetForm();
}
resetForm(form? : NgForm){
if(form != null)
form.resetForm();
this.service.formData={
empid : null,
name : '',
empcode : '',
mobile : '',
role : ''
}
}
onSubmit(form: NgForm){
this.insertRecord(form);
}
insertRecord(form: NgForm){
this.service.postEmpdata(form.value).subscribe(res=>{
this.resetForm(form)
});
}
}
you need to add cors in backend side this is not a frontend issue
for example