Angular CORS request blocked

前端 未结 5 433
独厮守ぢ
独厮守ぢ 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: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 index.html

提交回复
热议问题