aurelia-fetch-client - a promise was rejected with

2019-06-26 02:58发布

问题:

I'm using the aurelia-fetch-client and I get this error when I send a request to my nodejs backend api:

Warning: a promise was rejected with a non-error: [object Response]
    at http://localhost:9000/scripts/vendor-bundle.js:39700:20
    at Array.reduce (native)
    at applyInterceptors (http://localhost:9000/scripts/vendor-bundle.js:39696:33)
    at processResponse (http://localhost:9000/scripts/vendor-bundle.js:39688:12)
    at http://localhost:9000/scripts/vendor-bundle.js:39603:18
From previous event:
    at http://localhost:9000/scripts/vendor-bundle.js:39602:24
From previous event:
    at HttpClient.<anonymous> (http://localhost:9000/scripts/vendor-bundle.js:39590:64)
    at HttpClient.fetch (http://localhost:9000/scripts/vendor-bundle.js:39574:23)
    at AuthService.login (http://localhost:9000/scripts/app-bundle.js:126:30)
    at Login.login (http://localhost:9000/scripts/app-bundle.js:190:30)
    at CallScope.evaluate (http://localhost:9000/scripts/vendor-bundle.js:24067:21)
    at Listener.callSource (http://localhost:9000/scripts/vendor-bundle.js:27508:42)
    at http://localhost:9000/scripts/vendor-bundle.js:27532:24
    at HTMLDocument.handleDelegatedEvent (http://localhost:9000/scripts/vendor-bundle.js:25721:11)

Everything works fine but this warning is very annoying and I have no idea how to fix it, here's the code that sends the request:

import {HttpClient, json} from 'aurelia-fetch-client';
import baseConfig from 'config';

export class AuthService {
    constructor() {
        this.http = new HttpClient().configure(config => {
            config
                .withBaseUrl(baseConfig.baseUrl)
                .useStandardConfiguration();
        });

        this.isAuthenticated = false;
    }

    login(credentials) {
        return this.http.fetch('/login', {
            method: 'post',
            body: json(credentials)
        })
            .then(res => {
                this.saveToken(res.token)
                return Promise.resolve();
            });
    }

    saveToken(token) {
        localStorage.setItem('token', token);
        this.isAuthenticated = true;
    }
}

Any help appreciated

回答1:

The aurelia-fetch-client standard configuration (applied in your code via .useStandardConfiguration()) rejects on non-success HTTP response status codes. There is a recent (closed) issue for this in the aurelia/fetch-client repo here. The fetch client is rejecting the promise with the response itself, and so the browser is complaining (it wants promises to only be rejected with instances of Error).

I addressed this in my own code by removing .useStandardConfiguration(), as I don't need it in this particular project. You can check out the source code to get more of a picture of what's going on with the configuration.