Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Can't use .then() on ember-ajax's Promise after code 201 #315

Open
jevanlingen opened this issue Sep 14, 2017 · 2 comments
Open

Can't use .then() on ember-ajax's Promise after code 201 #315

jevanlingen opened this issue Sep 14, 2017 · 2 comments
Assignees
Labels
Bug Issue relates to a problem in the `ember-ajax` codebase
Milestone

Comments

@jevanlingen
Copy link
Contributor

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?

@zharikovpro
Copy link

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.

@alexlafroscia alexlafroscia added this to the 4.0.0 milestone Jun 18, 2018
@alexlafroscia alexlafroscia added the Bug Issue relates to a problem in the `ember-ajax` codebase label Jun 18, 2018
@alexlafroscia alexlafroscia self-assigned this Jun 18, 2018
alexlafroscia added a commit that referenced this issue Jul 7, 2018
This was actually just about configuring jQuery correctly to prevent
parsing the response as JSON. Setting the `dataType` to `text` does this
correctly.

Closes #315
@alexlafroscia
Copy link
Collaborator

The solution here turned out to be setting the dataType to text; otherwise jQuery will attempt to convert the response to JSON automatically.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug Issue relates to a problem in the `ember-ajax` codebase
Projects
None yet
Development

No branches or pull requests

3 participants