Angular CORS request blocked

前端 未结 5 413
独厮守ぢ
独厮守ぢ 2020-12-14 23:22

I am trying to connect my Angular app with a simple REST server on express. The server only sends json data in reply to request. To add CORS suppor

相关标签:
5条回答
  • 2020-12-15 00:03

    In case you are using angular-cli, you can use a proxy:

    proxy.conf.json:

    {
      "/api": {
        "target": "http://localhost:8888",
        "secure": false
      }
    }
    

    Will redirect all requests with /api prefix to localhost:8888 without any cors issue.

    Offical docs: https://angular.io/guide/build#proxying-to-a-backend-server

    0 讨论(0)
  • 2020-12-15 00:12

    Firstly, the problem on the client was due to the behavior of Firefox opting in to handle pre-flight CORS. Instead of using GET method,OPTIONS method was used. As it is evident from my code, I do not have any handler for handling OPTIONS. After some googling, I came across this post on github: Express CORS middleware. Using this and making the following modifications to my client request headers, I was able to properly get it up and running. Here's the code:

    CORS Middleware:

    function myCors(req, res, nxt) {
        res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
        res.header('Access-Control-Allow-Methods', 'GET,PUT,OPTIONS');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Content-Type, Accept, Accept-Language, Origin, User-Agent');
        if(req.method === 'OPTIONS') {
            res.sendStatus(204);
        }
        else {
            nxt();
        }
    }`
    

    Mounting it to the app instance: app.use(myCors);

    On the Angular client side service:

    this.corsHeaders = new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:8888/'
    });
    // ... adding it to the request
    getContent(subs: Array<string>): Observable<IContent> {
    return (() => {
      return this.http.get<IContent>( (() => {
        let r = this.root;
        subs.forEach((s, i, a) => {
          if(i === a.length-1) {
            r += s;
          }
          else {
            if(s !== '/') {
              r += s;
            }
          }
        });
        return r;
      })(), {
        headers: this.corsHeaders
      });
    
    })();
    }
    

    Thanks everyone for their time and efforts.

    0 讨论(0)
  • 2020-12-15 00:20

    Allow Server side that you hit from angular JS, in that case you need to allow http://localhost:8888/ because that is your server side URL, angular run on http://localhost:4200. please check the Http. then it work

    0 讨论(0)
  • 2020-12-15 00:21

    In development environment(localhost),you can do it easily without following any of these hard steps.You can simply download https://addons.mozilla.org/firefox/addon/cors-everywhere/ if you are using firefox and i think there must be an extension for chrome also.After downloading it will come to the firefox menubar and then you can click it to activate it,thats all you can now access to all apis as it automatically sends header with all requests.For production environment you have to configure it from your server by adding access-control-allow-origin to * (all)

    0 讨论(0)
  • 2020-12-15 00:26

    Use this code and manage yourself according to your structure.

    app.use(
        cors({ 
            origin: http://localhost:4200, 
            methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
            allowedHeaders: [
                'Content-Type', 
                'Authorization', 
                'Origin', 
                'x-access-token', 
                'XSRF-TOKEN'
            ], 
            preflightContinue: false 
        })
    );
    
    app.get('/', (res, req, nxt) => {
        // only for adding cors on all requests
        nxt();
    });
    

    On Angular Side

    constructor(private http: HttpClient) {
      this.root = 'http://localhost:8888';  //remove
      this.corsHeaders = new HttpHeaders({
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Access-Control-Allow-Origin': '/' .  // edit 
      });
      //this.contents = '';
     }
    

    and use <base> index.html

    0 讨论(0)
提交回复
热议问题