angularjs - 无法将 Content-Type header 放入拦截器

标签 angularjs http

我有很多请求与这个结构相同:

angular.module( 'factories' )
  .factory( 'encodedFormInterceptor', function( $window, $q, $http ) {
    return {
      request: function( config ) {
        config.headers = config.headers || {};
        config.headers.Content-Type = 'application/x-www-form-urlencoded';

        return config || $q.when( config );
      },
      response: function( response ) {
        if ( response.status === 401 ) {

        }
        return response || $q.when( response );
      }
    };
  } );

但是当我尝试在单独的拦截器中设置 Content-Type header 时,如下所示:

angular.module( 'factories' )
  .factory( 'encodedFormInterceptor', function( $window, $q, $http ) {
    return {
      request: function( config ) {
        config.headers = config.headers || {};
        config.headers.Content-Type = 'application/x-www-form-urlencoded';

        return config || $q.when( config );
      },
      response: function( response ) {
        if ( response.status === 401 ) {

        }
        return response || $q.when( response );
      }
    };
  } );

我收到这个错误:

ReferenceError: invalid assignment left-hand side

config.headers.Content-Type = 'application/x-www-form-urlencoded';

我已经在使用另一个拦截器进行授权,效果很好:

angular.module( 'factories' )
  .factory( 'AuthInterceptor', function( $window, $q ) {
    return {
      request: function( config ) {
        config.headers = config.headers || {};
        if ( $window.localStorage.getItem( 'eva-token' ) ) {
          config.headers.Authorization = 'Bearer ' + $window.localStorage.getItem( 'eva-token' );
        }
        return config || $q.when( config );
      },
      response: function( response ) {
        if ( response.status === 401 ) {

        }
        return response || $q.when( response );
      }
    };
  } );

那么我怎样才能把其他的头部类型放到拦截器中呢?我检查了 AngularJS 文档,但在那里没有找到答案。

最佳答案

您不能在变量名中使用-。 尝试:

config.headers["Content-Type"] = 'application/x-www-form-urlencoded';

关于angularjs - 无法将 Content-Type header 放入拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34118635/

相关文章:

php - ajax请求并发数最大限制

http - 在 Neo4j 服务器中为每个单独的时间记录 http 请求/响应

html - Angular Material 工具栏高度问题

javascript - Angularjs popover nglick 第二次不会触发

angularjs - 两个指令(未嵌套在 HTML 中)如何相互通信?

c - 在 C 中访问 Gmail

java - 检查 URL 是 HTTPS 还是 HTTP 协议(protocol)?

javascript - 如何在没有 Controller 的情况下使用 ng-class ?

javascript - 如何删除范围变量中存在的重复项

java - 如何在 Java 中发出 http 部分 GET 请求