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

后端 未结 7 760
独厮守ぢ
独厮守ぢ 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:11

    Victor K had the solution, I'll just add this comment here as to what I did:

    I created the component "ExRequestOptions" as Victor K said, but I also added a method "appendHeaders" to that component:

    appendHeaders(headername: string, headervalue: string) {
        this.headers.append(headername, headervalue);
    }
    

    Then I had this in my main.ts:

    import {bootstrap}    from 'angular2/platform/browser'
    import {AppComponent} from './app.component'
    import {HTTP_PROVIDERS, RequestOptions} from 'angular2/http';
    import 'rxjs/Rx';
    import {ExRequestOptions} from './transportBoxes/exRequestOptions';
    import {provide} from 'angular2/core';
    
    bootstrap(AppComponent,[ HTTP_PROVIDERS,  
        provide(RequestOptions, {useClass: ExRequestOptions})]);
    

    I'm not sure the bootstrapping had any effect, so i also did this where I would post data:

        let options = new ExRequestOptions();
        options.appendHeaders('Content-Type', 'application/json');
        return this.http.post('.....URL', JSON.stringify(registration),
             options)
    

提交回复
热议问题