Vladimir Oselsky
Vladimir Oselsky

Reputation: 113

Problem calling webservice, possibly related to CORS

I'm building angular app using VSCode, trying to call Web Service API built in ASP.NET core, I have tested web api using Postman and it works just fine.

When calling from angular app I get the following error

student-registration.component.ts:177 error
student-registration.component.ts:178 SyntaxError: Unexpected end of input
    at trainingcreditvalidation.service.ts:43
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.js:17299)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
    at zone.js:889
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)

Here is my code for service piece

  getTraining()
  {
    console.log( 'gettraninig' );

    return fetch( 'http://localhost:51218/api/traininig/test', { mode: 'no-cors' } )
      .then( response => response.json() );
  }

and then the component making the call

    this.trainingCreditService.getTraining().then( ( response ) =>
    {
      response.json().then( ( data ) =>
      {
        console.log( 'TC Fetch: ' + JSON.stringify( data ) );
      } );
    } ).catch( ( err ) =>
    {
      console.log( err );
    } );

I made it based on the example in Fetch API. If I take out { mode: 'no-cors' } i get CORS Error

Upvotes: 0

Views: 67

Answers (1)

asimhashmi
asimhashmi

Reputation: 4378

Try changing your code like this:

this.trainingCreditService.getTraining()
 .then( ( response ) => {
    console.log("TC Fetch", response)
    } )
 .catch( ( err ) => console.log( err ));

You have messed up some brackets, also the data coming from getTraining() is already in json format (you already converted it to json in your getTraining() method). So there is no need to call json() on it.

When calling API with fetch, you need to set your request mode to 'cors':

getTraining()
  {
    console.log( 'gettraninig' );

    return fetch( 'http://localhost:51218/api/traininig/test', { mode: 'cors' } )
      .then( response => response.json() );
  }

This is due to the Cross Origin Resource Sharing(CORS). By default the browsers don't allow any script running on one domain to access resource on another domain. So you need to add extra headers in your request to tell the browser to allow this request and setting the mode to cors does that for you.

You can find more information here about CORS

Also have a look at different modes in fetch API

Upvotes: 2

Related Questions