0

When I tried to pass values from one server to other server am getting error as "Access to XMLHttpRequest at 'http://localhost:8082/kanchiwork/' from origin 'http://localhost:4200' has been blocked by CORS policy". My .ts file code

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PeopleService {

  constructor(private http:HttpClient) { }

  fetchPeople(): Observable<Object>{
    return this.http.get('http://localhost:8082/kanchiwork/');
    //return this.http.get('assets/response.json');
  }

}

where as if I placed the json file(response.json) in assets folder, it is working fine. I have followed the instruction given under the heading "Using corporate proxy" in the below URL, but still problem exists. URL : https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

Venkat
  • 85
  • 1
  • 10
  • 1
    Does this answer your question? [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Andrew Allen Feb 26 '20 at 07:11

5 Answers5

1

For developing, You can define a proxy.dev.conf.json file to manage your request with Angular cli. eg: ng serve --open --proxy-config ./proxy.dev.conf.json

// config

[
  {
    "context": [
      "/api/**"
    ],
    "pathRewrite": {
      "^/api": ""
    },
    "ws": false,
    "target": "http://localhost:8082",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
]

// the service file
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PeopleService {

  constructor(private http:HttpClient) { }

  fetchPeople(): Observable<Object>{
    return this.http.get('/api/kanchiwork/');
    //return this.http.get('assets/response.json');
  }

}

xsong
  • 630
  • 1
  • 5
  • 18
  • I have created a file "proxyconfig.json" and added the below code `[ { "context": [ "/api/**" ], "ws": false, "target": "http://localhost:8082", "secure": false, "changeOrigin": true, "logLevel": "debug" } ]` by removing comma "," after "/api/**". I started the service by ng serve --open --proxy-config ./proxyconfig.json, but still problem persists. Anything I did wrong? – Venkat Feb 26 '20 at 07:45
  • The `/api/**` is a prefix of your API address, It's an anchor to resolve which request will be proxy.And the code in the service file will change to `/api/kanchiwork/` , and the config file will add a rule to rewrite. I will update the answer. – xsong Feb 26 '20 at 09:48
  • If there are some errors emitted, please let me know. – xsong Feb 26 '20 at 09:51
  • Thanks @xsong, am getting message as "GET http://localhost:4200/api/kanchiwork/ 404 (Not Found)" in console – Venkat Feb 26 '20 at 10:22
  • 404 shows the URL proxy to 8082 is not the `http://localhost:8082/kanchiwork/`, you can look at the log of the `8082 server`. – xsong Feb 27 '20 at 01:55
0

Venkat, its not your fault because backend uses allow cross origin functionality on his side so that frontend not getting CORS error..

its error comes when you comes different url or port like cross domain.

0

Generally CORS error Means - CROSS ORIGIN RESOURCE SHARING it helps us to block request from Unwanted Sources, Which inturn increases security to our application, Your backend develepors should allow your url,

eg: if your backend developed in node js ask your team to add this code

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'example.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

//...
app.configure(function() {
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: 'cool beans' }));
    app.use(express.methodOverride());
    app.use(allowCrossDomain);
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});
ajay
  • 113
  • 3
  • 10
  • There is nothing wrong from your side , in postman you will get response , because post man doesnt care about CORS POLICY, its just a console application – ajay Feb 26 '20 at 07:04
0

The proxy.conf path proposed by @xsong is correct, you just need to tweak it a little. First: don't hardcode the API path in the app itself (it's good practice anyway, regardless of proxy/no proxy/CORS/no CORS), put it in the environment.ts file. For developer build, you may define it simply as apiUrl: "/api".

Then, in your service(s), import the environment, send your requests at ${environment.apiUrl}/the-rest/of-the-path. And the third piece, you might need to rewrite path in the proxy.conf:

  {
    "context": [
      "/api/**",
    ],
    "target": "http://localhost:8082",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug",
    "pathRewrite": {
       "^/api": ""
    }
  }
mbojko
  • 13,503
  • 1
  • 16
  • 26
  • Thanks for your response @mbojko , could you please explain in a little bit please. – Venkat Feb 26 '20 at 09:26
  • Your app still has hardcoded `http://localhost:8082` as the base path of your API, and it'll try to access that host. For the proxy.conf entry for `"context": ["/api/**"]` be relevant, your app must make (try to make) HTTP calls to `/api/something` in the first place. – mbojko Feb 26 '20 at 09:31
  • Okay, now I have create a API in the following path `https://www.kanchikart.in/api/test_details/` and as you suggested I did but still same issue.In proxyconfig.json file the code am using is `[ { "context": [ "/api/**" ], "ws": false, "target": "https://www.kanchikart.in/api/test_details/", "secure": false, "changeOrigin": true, "logLevel": "debug" } ]` – Venkat Feb 26 '20 at 09:49
0

It gets works by updating the files to the below ones.In proxy.config.json I updated the code as

{
  "/api": {
    "target": "http://localhost:8082",
    "secure": false
  },
  "logLevel": "debug"    
}

and in service file

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PeopleService {

  constructor(private http:HttpClient) { }

  fetchPeople(): Observable<Object>{
    return this.http.get('/api/kanchiwork/');
    //return this.http.get('assets/response.json');
  };

}

This code works for me and Thanks @xsong for your suggestions.

Venkat
  • 85
  • 1
  • 10