通过 ajaxSetup (Ember) 在模型挂钩中设置 headers

Setting headers in the model hook via ajaxSetup (Ember)

我试图在拨打电话之前设置 header,但它不起作用。

model: function() {
        debugger;

        Ember.$.ajaxSetup({
            beforeSend: function(xhr) {
                xhr.setRequestHeader(
                    'Authorization', 'bearer 123456'
                )
        }});

        return Ember.$.getJSON('http://addresss/api/locations').then(function(e) {
            debugger;
            console.log(e);
        });
    }

这一直给我以下错误信息:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

如果我使用 Postman 并设置我的 header 它工作正常。

有时将 xhr 字段 - withCredentials - 设置为 true 有助于克服此类错误。请尝试:

Ember.$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.withCredentials = true;
        xhr.setRequestHeader('Authorization', 'bearer 123456');
    }
});