For reference I'm using Visual Studio 2017 and Windows 10.
I have a web api and corresponding web application with user accounts. When I attempted to login I was met with an error which said No Access-Control-Allow-Origin header is present. I found a guide that walked me through how to setup CORS. This is the guide I used.
https://social.technet.microsoft.com/wiki/contents/articles/33771.fix-to-no-access-control-allow-origin-header-is-present-or-working-with-cross-origin-request-in-asp-net-web-api.aspx
In my WebApiConfig file I have this code
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
In my AccountController file I added in the EnableCors at the top.
[EnableCors(origins: "*", headers: "*", methods: "*")]
[Authorize]
[RoutePrefix("api/Account")]
Finally, in my Web.config file I added the following:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
This fixed my login issue however, none of my GETS are working. Here is an example of a GET function:
jQuery.support.cors = true;
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'http://localhost:60690/api/ProfilePicture?Username=' + username, false);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'));
xmlhttp.send();
if (xmlhttp.status == 200) {
returnValue = jQuery.parseJSON(xmlhttp.responseText);
}
}
The GET is throwing an error which says "Multiple Access-Control-Allow-Origin headers are not allowed for CORS response". I don't see where I have multiple Access-Control-Allow-Origin headers anywhere. Where should I be looking?
Update 1
Found something interesting. I used Fiddler to watch everything going on in the background and on the GET function that causes the error I'm seeing this in the headers:
So the "Access-Control-Allow-Origin: *" is definitely showing twice but the question is why. I searched all of my code and I only have that declared once. If I remove that line, it breaks the login page so I have to leave it in.
I think I figured this out. I went into the WebApiConfig file and changed the part about CORS to this:
//var cors = new EnableCorsAttribute("*", "*", "*");
//config.EnableCors(cors);
config.EnableCors();
Then I removed the EnableCors part from my Controller and it sort of started working again. I'm still getting an error on the GET call but I went from two errors to just one so it's progress I guess.
Related
For reference I'm using Visual Studio 2017 and Windows 10.
I have an MVC webapi project designed using a template provided by Visual Studio with accounts that are stored in an SQL database. I have another project which is the website itself that the users log into. I'm attempting to debug in VS but am being met with an access is denied error message whenever a GET request is made outside of the initial login. I've enabled CORS on the webapi but it didn't seem to make much of a difference.
Here's how I enabled CORS.
In the WebAPIConfig file I have the following:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And then in the Web.config file I have this:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
This is the code from the website making the call:
function getProfilePicture(username){
var returnValue = [];
jQuery.support.cors = true;
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'http://localhost:60690/api/ProfilePicture?Username=' + username, false);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'));
xmlhttp.send();
if (xmlhttp.status == 200) {
returnValue = jQuery.parseJSON(xmlhttp.responseText);
}
}
return returnValue;
}
The error message says "SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied."
Did I not properly enable CORS?
Update
I downloaded Postman in an attempt to figure out the issue. I'm actually able to make GET calls with Postman without any errors. It's returning the data and everything. One thing I did notice is it doesn't look like the Authorization header is actually being sent. It's missing from the data in Fiddler.
Specifying Access-Control-Allow-Credentials: true as a response header is incompatible with Access-Control-Allow-Origin: *. If you're going to use credentials, you must use Access-Control-Allow-Origin: <value-of-origin-request-header>.
i am using default webapi ApplicationOAuthProvider code below to login. and i add in
<add name="Access-Control-Allow-Origin" value="*" />
in the web.config and client is able to login via www.testapi.com/token.
everything works fine.
But when i create a custom webapi function. it is still asking me for access-origin control to enable. So i do so by adding this line of code in WebapiConfig.cs
EnableCorsAttribute cors = new EnableCorsAttribute("http://www.myweb.com:82", "*", "*");
config.EnableCors(cors);
this time it prompt error saying
''Access-Control-Allow-Origin' header contains multiple values 'http://www.myweb.com:82, *', but only one is allowed. Origin 'http://www.myweb.com:82' is therefore not allowed access.
so i remove the <add name="Access-Control-Allow-Origin" value="*" /> in the web.config and it works!!.
i return to the login and it is asking for <add name="Access-Control-Allow-Origin" value="*" /> to be added. but if i add this in. my webapi method will not be able to call.
if i dont add. client will not be able to log in.
is there a way for both to work?
below is the response of 200 with error.
Update 1
startup.auth.cs
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);//as instructed
webapiconfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
WebApiConfig.Register(config);
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
//var jsonp = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
//config.Formatters.Insert(0, jsonp);
}
}
Install Microsoft.AspNet.WebApi.Cors nuget package
Install Microsoft.Owin.Cors nuget package
Add config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE")); to the above of WebApiConfig.Register(config); line at Startup.cs file.
Add app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); to the Startup.Auth.cs file. This must be done prior to calling IAppBuilder.UseWebApi
ok finally i managed to get it work with help from "#manprit Singh Sahota"
i remove all the access policy from web.config.
and also the line below in WebApiConfig
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
i only add this line to the Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);//working line
I have three applications in my architecture.
They are on the same server but having different port numbers.
A - Token Application (port 4444) - Asp.net WebApi
B - API Application (port 3333) - Asp.net WebApi
C - UI Application (port 2222) - AngularJS App.
The application flow is like below
1- The UI project gets the token from Token Application (It requires Windows Auth.)
Ex : awxrsdsaWeffs12da
2- UI application puts this token to a custom header which is named as "accessToken"
Ex : accessToken : awxrsdsaWeffs12da
3- UI application sends a request to API Application
Ex: http:myaddress:3333/api/TheRestServiceHere
UI application gets 401 Error.
Which sends OPTIONS method. (I guess preflight issue)
In my web api project I enabled Cors like this below.
public static void Register(HttpConfiguration config)
{
....
//CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
....
}
Config
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
json.SerializerSettings.Formatting = Formatting.None;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
So I am looking for a solution to call API application (B) controllers
and get 200 :)
Regards
I fixed this in an application I am working on by creating a module that responds to requests that are using the OPTIONS verb. You should probably modify it a bit to include the verbs and content type that the application is requesting. In my case, I decided to post everything as JSON (which requires the pre-flight check). The module is as follows:
public class OptionsModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, args) =>
{
var app = (HttpApplication) sender;
if (app.Request.HttpMethod == "OPTIONS")
{
app.Response.StatusCode = 200;
app.Response.AddHeader("Access-Control-Allow-Headers", "content-type");
app.Response.AddHeader("Access-Control-Allow-Origin", APISettings.ApplicationOrigin);
app.Response.AddHeader("Access-Control-Allow-Credentials", "true");
app.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
app.Response.AddHeader("Content-Type", "application/json");
app.Response.End();
}
};
}
public void Dispose()
{
}
}
Then you need to register it in your web.config:
<system.webServer>
<modules>
<add name="HandleOptions" type="namespace.OptionsModule" />
</modules>
</system.webServer>
Another thing you may want to do is specify the allowed origin explicitly. Chrome doesn't like having a wildcard there.
One of my friend solved the issue by using OPTIONSVerbHandler.
When UI application wants to use GET method, browser sends
OPTION method first to the server (Preflight). Then if Preflight request is OK it sends GET request.
For CORS test purpose we used the following code to send GET method.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
var adress = "http://10.10.27.36:3434/backend/api/role";
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'accessToken': 'some value',
'Origin' : ''
}
});
$.ajax({
type: "GET",
url: adress,
dataType: "json"
});
});
</script></head><body></body></html>
To handle OPTION method which sends by browser before GET you should have the following settings.
1- Webconfig
<system.webServer>
<handlers>
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="None" />
</handlers>
</system.webServer>
2- Adding OPTIONSVerbHandler with following settings
Click on request restrictions
3- Our Header Settings we have accessToken which is custom as you can see
This problem happened for Cordova v11, platform for Android. I used the solution provided by Jereme (the top rated answer) with one exception: In OptionsModule, I had to omit the statement
app.Response.AddHeader("Access-Control-Allow-Origin", APISettings.ApplicationOrigin);
Instead in the web.config file I added in the <system.webServer> section the following:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<!-- Note: "localhost" for Cordova is not valid, only * worked. -->
</customHeaders>
</httpProtocol>
A word about Cordova in case one is unfamiliar. Cordova packages a native app for the Android platform with a “javascript page” included in the app, using a web view in the app to display the page. Using the Chrome debugger to view the javascript page, the page origin appears as localhost. However, localhost is not an acceptable value for the Access-Control-Allow-Origin header; therefore I had to use “*” in the Web.config file. When I had the response header in the OptionsModule, the preflight response was ok (status 200), but not the response for the XMLHttpRequest (the api) that initiated the preflight request. Putting the custom header only in the Web.config file allowed both responses to be ok (status 200).
For Azure Environment
You need allow origins from the portal.
I have client and a server running on different ports. The server is running Web API 2 (v5.0.0-rc1).
I tried installing the Microsoft ASP.NET Web API Cross-Origin Support package and enabled it in WebApiConfig.cs. It gives me the EnableCors() function, so the package was installed correctly.
Here you can see my Register() function in WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
GET requests work fine. But when sending POST, I get the following:
OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159
OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159
XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.
According to Fiddler it only sends the OPTIONS request. It doesn't issue the POST afterwards.
So I'm guessing the config.EnableCors(cors); in the WebApiConfig.cs isn't doing anything, which leads to the server denying the client/browser to send a POST request.
Do you have any idea how to solve this problem?
EDIT 05.09.13
This has been fixed in 5.0.0-rtm-130905
CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors version 5.2.2. The following steps configured CORS like a charm for me:
Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" // run from Package manager console
In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS
GlobalConfiguration.Configure(WebApiConfig.Register);
In the WebApiConfig Register method, have the following code:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
}
In the web.config, the following handler must be the first one in the pipeline:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
In the controller derived from ApiController, add the EnableCorsAttribute:
[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController
That should set you up nicely!
I didn't need to install any package. Just a simple change in your WebAPI project's web.config is working great:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
Credit goes to: Using CORS in ASP.NET WebAPI Without Being a Rocket Scientist
For reference using the [EnableCors()] approach will not work if you intercept the Message Pipeline using a DelegatingHandler. In my case was checking for an Authorization header in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()] had no effect.
In the end found an example CrossDomainHandler class (credit to shaunxu for the Gist) which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.
public class CrossDomainHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
To use it add it to the list of registered message handlers
config.MessageHandlers.Add(new CrossDomainHandler());
Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions] IHttpActionResult method on the Controller.
I'm most definitely hitting this issue with attribute routing. The issue was fixed as of 5.0.0-rtm-130905. But still, you can try out the nightly builds which will most certainly have the fix.
To add nightlies to your NuGet package source, go to Tools -> Library Package Manager -> Package Manager Settings and add the following URL under Package Sources: http://myget.org/F/aspnetwebstacknightly
Make sure that you are accessing the WebAPI through HTTPS.
I also enabled cors in the WebApi.config.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
But my CORS request did not work until I used HTTPS urls.
Late reply for future reference. What was working for me was enabling it by nuget and then adding custom headers into web.config.
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);
This solved my issue:
in Web.config>>Inside system.webServer tags:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
And uncomment or delete this line inside system.webServer:
<remove name="OPTIONSVerbHandler"/>
Also, you need to declare enable cors either in webapiconfig.cs or in web.config. If you declare in both you may get an error something like :
'....origin 'www.example.com' blocked by cors policy due to multiple No 'Access-Control-Allow-Origin'('*','*').'
This did the trick for me.
To enable CORS,
1.Go to App_Start folder.
2.add the namespace 'using System.Web.Http.Cors';
3.Open the WebApiConfig.cs file and type the following in a static method.
config.EnableCors(new EnableCorsAttribute("https://localhost:44328",headers:"*", methods:"*"));
As far as I understood, the server got to have a header that specifies that Access from Origin is Allowed i.e. a request from the same server could be responded to.I used the following code :
// create a response object of your choice
var response = Request.CreateResponse(HttpStatusCode.OK);
//add the header
//replace the star with a specific name if you want to restrict access
response.Headers.Add("Access-Control-Allow-Origin", "*");
//now you could send the response and it should work...
return response;
Below code worked for me,
App_Start -> WebApiConfig
EnableCorsAttribute cors = new EnableCorsAttribute("\*", "\*", "GET,HEAD,POST");
config.EnableCors(cors);
Is it possible to implement "Access-Control-Allow-Origin" header in asp.net
From enable-cors.org:
CORS on ASP.NET
If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
See also: Configuring IIS6 / IIS7
Another option is to add it on the web.config directly:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
...
I found this in here
1.Install-Package Microsoft.AspNet.WebApi.Cors
2 . Add this code in WebApiConfig.cs.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
3. Add this
using System.Web.Http.Cors;
4. Add this code in Api Controller (HomeController.cs)
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
[HttpGet]
[Route("api/Home/test")]
public string test()
{
return "";
}
}
You would need an HTTP module that looked at the requested resource and if it was a css or js, it would tack on the Access-Control-Allow-Origin header with the requestors URL, unless you want it wide open with '*'.
Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.
Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:
{
"/api": {
"target": "http://localhost:49389",
"secure": true,
"pathRewrite": {
"^/api": "/api"
},
"changeOrigin": true
}
}
Put the file in the same directory the package.json then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from the app component is as follows:
return this.http.get('/api/customers').map((res: Response) => res.json());
Lastly to run use npm start or ng serve --proxy-config proxy.conf.json