take
take

Reputation: 2222

$.ajaxPrefilter throws Uncaught TypeError: Cannot convert null to object Exception

I want to change the AJAX Header with $.ajaxPrefilter and tried following:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    delete options.headers["myOwnHeader1"];
    options.headers["myOwnHeader2"] = "test";
});

In the Network Console (Chrome) the myOwnHeader2 is set and the myOwnHeader1 not. But it throws the following Exception: Uncaught TypeError: Cannot convert null to object on options.headers["myOwnHeader2"] = "test";

Upvotes: 2

Views: 3480

Answers (1)

Bergi
Bergi

Reputation: 665256

The options object does not necessarily contain a headers property - only if given in the global $.ajaxSettings or in the current (original) options. So your choices are

  • using $.ajaxSetup({headers: {}});, maybe with the myOwnHeader2 already set
  • wrapping your delete/extend operations in a if ("headers" in options) block
  • creating the headers object dynamically in the prefilter if it does not exists:

options.headers = options.headers || {};
delete options.headers["myOwnHeader1"];
options.headers["myOwnHeader2"] = "test";

Upvotes: 1

Related Questions