ember-ajax
ember-ajax copied to clipboard
Can't use .then() on ember-ajax's Promise after code 201
This issue is related with Can't use .then() on ember-ajax's Promise after code 200.
My backend returns a 201 status code with an empty response and location header after a new user is created. According to the specs that should be enough (easier explanation).
With plain jQuery you can use the success callback, if you leave the "dataType" unsetted. So following ajax call works fine:
Ember.$.ajax({
url: '/user/create',
data: JSON.stringify(data),
contentType: 'application/json',
type: 'POST'
}).then( (data, status, xhr) => {
console.log(xhr.getResponseHeader('Location'));
}, error => {
alert(error.responseJSON.errorMessage);
});
If I rewrite following code with the ember-ajax addon:
this.get('ajax').post('user/create', {
data: JSON.stringify(data),
contentType: 'application/json'
}).then( () => {
//location header is only available by the this.get('ajax').raw function, so just print something...
console.log('user has been created!')
}).catch( error => {
alert(error.payload.errorMessage);
});
After a new user has successfully been created, the catch
is called! Is there something I should change or should I consider this a ember-ajax bug?
Is there something I should change
There are two options on the backend:
a) return 204 No content status, that way Ember will not try to parse response body which causes an error b) return valid JSON body (even empty object, but not an empty string), so that Ember can parse the response without an error.
The solution here turned out to be setting the dataType
to text
; otherwise jQuery will attempt to convert the response to JSON automatically.