我正在尝试为我的emberjs应用程序设置请求标头。 虽然在初始化程序中执行相同操作,但它确实已注册并注入,但在请求标头中client_id作为[object Object] 这是应用程序启动时触发的初始化程序。
Apikey //app/initializers/apikey.js
export default {
name: "apikey",
initialize: function(container, application) {
//application.deferReadiness();
var data = {"business" : window.location.host};
$.ajax({
url: ENV.apiKeyEndpoint,
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data)
}).done(function(results){
console.log(results.apikey.client_secret);
container.register("business:key", results.apikey.client_id, { instantiate: false });
container.register("business:secret", results.apikey.client_secret, { instantiate: false });
container.injection('controller', 'apiKey', 'business:key');
container.injection('route', 'apiKey', 'business:key');
container.injection('serializer', 'apiKey', 'business:key');
container.injection('data-adapter', 'apiKey', 'business:key');
});
}
};
app/adapters/application.js //app/adapters/application.js
export default DS.RESTAdapter.extend({
// ToDo:: Add headers so that the backend will get notify which client it is.
headers: {
'client_id': function() {
return this.get("apiKey");
}.property("apiKey"),
},
host: ENV.apiEndpoint
});
我得到的回应:: request headers
//来自apikey初始化程序
{
"apikey": {
"client_id": "0.0.0.0:4300",
"client_secret": "kjahsdyau89dfuaoisduoaisu",
"redirect_uri": "",
"grant_types": null,
"scope": null,
"user_id": null
}
}
//request headers
Accept: application / json,
text / javascript,
*
/*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
client_id:[object Object]
Connection:keep-alive
Host:api.app
Origin:http://0.0.0.0:4300
Referer:http://0.0.0.0:4300/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1964.2 Safari/537.36*/
答案 0 :(得分:0)
Ember Data does not invoke values in the headers
hash if they are functions。您的client_id
标题不会像我认为的那样被调用;它只是直接被强制进入XMLHttpRequest#setRequestHeader
内的某个字符串。
您可以覆盖RESTAdapter#ajaxOptions
来自定义行为,例如:
export default DS.RESTAdapter.extend({
customHeaders: {
client_id: function(adapter) {
return adapter.get('apiKey');
}
},
ajaxOptions: function() {
var adapter = this;
var hash = this._super.apply(this, arguments);
var headers = this.customHeaders;
if (headers) {
hash.beforeSend = function (xhr) {
Ember.keys(headers).forEach(function(key) {
var value = headers[key];
if (Ember.typeOf(value) === 'function') {
// Pass the adapter instance when invoking the `customHeader` functions
value = value.call(null, adapter);
}
xhr.setRequestHeader(key, value);
});
};
}
return hash;
}
});
更新:现在使用适配器作为第一个参数而不是上下文调用customHeader
函数。