Skip to content
Fred Chien edited this page Nov 1, 2015 · 5 revisions

We always design and implement restful APIs which is accessed by client only, but isomorphic app is not. It needs a way to access APIs from client and server both and just write once is good.

Extension for API Request

With API Request Extension provided, you can send request to server and access APIs with simple method. It was attached to FLUX instance, so you can use it everywhere.

In fact, this extension is based on superagent, the most of superagent methods can be used directly. All of methods will return a thunk, you have to call with yield in generator function.

GET

var res = yield this.flux.request
    .get('/apis/article/1')
    .query();

POST

var res = yield this.flux.request
    .post('/apis/article')
    .send({
        title: 'Hello',
        text: 'Good'
    });

PUT

var res = yield this.flux.request
    .put('/apis/article')
    .send({
        title: 'Hello',
        text: 'Good'
    });

DELETE

var res = yield this.flux.request
    .del('/apis/article/1')
    .query();

Send Request from Stores or Actions

Here is an example to show how to send a request from store:

export default function *() {
    this.on('store.Foo.doSomething', function *() {
        try {
            var res = yield this.request
                .get('/apis/article/1')
                .query();

            console.log(res.body);
        } catch(e) {
            switch(e.status) {
            case 500:
            case 400:
                console.log('Something\' wrong');
                break;
            }
        }
    });
};

Clone this wiki locally