What is the right way to use angular2 http requests with Django CSRF protection?

后端 未结 7 762
独厮守ぢ
独厮守ぢ 2020-11-28 13:23

In Angular1 the problem can be solved by configuring $http-provider. Like:

app.config(function($httpProvider) {
  $httpProvider.defaults.xsrfCookieName = \'c         


        
7条回答
  •  感情败类
    2020-11-28 14:14

    Currently, I solve anything with custom headers using a wrapper service around the Http Service. You can add whatever header manually and inject additional services for storing/retrieving values. This strategy also works for JWTs, for example. Have a look at the code below, I hope it helps.

    import {Injectable} from '@angular/core';
    import {Http, Headers, RequestOptions} from '@angular/http';
    
    @Injectable()
    export class HttpService {
      constructor(private http: Http) {
      }
    
      private get xsrfToken() {
        // todo: some logic to retrieve the cookie here. we're in a service, so you can inject anything you'd like for this
        return '';
      }
    
      get(url) {
        return this.http.get(url, this.getRequestOptions())
          .map(result => result.json())
          .catch(error => error.json());
      }
    
      post(url, payload) {
        return this.http.post(url, payload, this.getRequestOptions())
          .map(result => result.json())
          .catch(error => error.json());
      }
    
      private getRequestOptions() {
        const headers = new Headers({'Content-Type': 'application/json', 'X-XSRF-TOKEN': this.xsrfToken});
        return new RequestOptions({headers: headers});
      }
    }
    

提交回复
热议问题