Coder Social home page Coder Social logo

http-client's Introduction

aurelia-http-client

npm Version ZenHub Join the chat at https://gitter.im/aurelia/discuss CircleCI

This library is part of the Aurelia platform and contains a simple, restful, message-based wrapper around XMLHttpRequest.

To keep up to date on Aurelia, please visit and subscribe to the official blog and our email list. We also invite you to follow us on twitter. If you have questions look around our Discourse forums, chat in our community on Gitter or use stack overflow. Documentation can be found in our developer hub. If you would like to have deeper insight into our development process, please install the ZenHub Chrome or Firefox Extension and visit any of our repository's boards.

Documentation

If possible, prefer to use the aurelia-fetch-client instead of this library. You can read documentation on the fetch client here along with documentation on this library. If you would like to help improve this documentation, the source for these docs can be found in the aurelia-fetch-client repo's doc folder.

Platform Support

This library can be used in the browser only.

Building The Code

To build the code, follow these steps.

  1. Ensure that NodeJS is installed. This provides the platform on which the build tooling runs.
  2. From the project folder, execute the following command:
npm install
  1. Ensure that Gulp is installed. If you need to install it, use the following command:
npm install -g gulp
  1. To build the code, you can now run:
gulp build
  1. You will find the compiled code in the dist folder, available in three module formats: AMD, CommonJS and ES6.

  2. See gulpfile.js for other tasks related to generating the docs and linting.

Running The Tests

To run the unit tests, first ensure that you have followed the steps above in order to install all dependencies and successfully build the library. Once you have done that, proceed with these additional steps:

  1. Ensure that the Karma CLI is installed. If you need to install it, use the following command:
npm install -g karma-cli
  1. Ensure that jspm is installed. If you need to install it, use the following commnand:
npm install -g jspm
  1. Install the client-side dependencies with jspm:
jspm install
  1. You can now run the tests with this command:
karma start

http-client's People

Contributors

aaike avatar alexanderchr avatar andrew-w-ross avatar behzad888 avatar brettmn avatar bryanrsmith avatar cmichaelgraham avatar davismj avatar derekpitt avatar doktordirk avatar eisenbergeffect avatar fkleuver avatar fragsalat avatar gamtiq avatar gregoryagu avatar jmvtrinidad avatar jwahyoung avatar louislewis2 avatar martingust avatar maurice-camp avatar micahzoltu avatar mordred avatar npelletm avatar plwalters avatar pndewit avatar reinholdk avatar strahilkazlachev avatar sujesharukil avatar vuorinem avatar zewa666 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

http-client's Issues

Provide a way to ignore content transformation

jQuery's ajax has processData: false to prevent stringifying content. Aurelia's contentTransformer has no way of preventing JSON.stringify if content should not be stringified. Provide a way to not call contentTransformer if a flag is set to false.

Easier header management

It would be nicer if we could supply an array of headers to outgoing calls or something similarly easy. If there is already a preferred way for us to manage headers that would be a good thing to add to the docs.

Unable to change Content-Type header

I would like to override Content-Type header when using this.http.put() and post.
The default content type is "text/plain;charset=UTF-8" but I need "application/json".
I tried to attach .withHeaders({ "Content-Type": "application/json" }) to put method, but it didn't work.
Please provide a way to set this header. Thanks!

No header returned in response

I think returned headers are missing in response.
Below the code example and screenshots

return this.http.post(this.url, this.credentials).then(response => {
        console.log(response.getAllResponseHeaders());
});              

2

1

jspm package does not contain the interceptor functionality.

My apologies upfront for not being hindered too much by in depth jspm knowledge, but the jspm package for http-client 0.8.1 doesn't seem to contain the interceptor functionality in github for the same version.
What is precisely workflow here ?
In github I would expect that in the dist/system folder, the up to date compiled stuff would be present ? There is still an old 'build'. I guess jspm is taken its sources from there.

No authorization header is sent using .withHeader('Authorization', 'Bearer 123')

Part A)
Using the latest release, if you configure an HttpClient as with Authorization headers as such:

this.httpClient.configure((x) => x.withHeader('Authorization', 'Bearer ' + common.getAccessToken())

Then these authorization headers are SET, but never SENT.
The reason seems to be that authorization headers are never included if the call is not a CORS request.
I think this should be clarified in the docs and in issue #19 for future reference (which will happen as soon as I submit this...)

Part B)
I'm not sure if Authorization headers for CORS requests are sent unless you explicitly set withCredentials(true), based on the spec and this blog post.
If this is true, would we not want to design the API in such a way that you cannot set the Authorization header if withCredentials is not also set? Either way, if this is true, we definitely need to update the docs as they do set the Authorization without calling.withCredentials(true)

client.createRequest('some/cool/path')
  .asGet()
  .withBaseUrl('http://aurelia.io')
  .withHeader('Authorization', 'bearer 123')
  .send();

Cannot set header in 0.5.2

Hi! I'm not able to set a header on 0.5.2, neither by using the configure function nor the withHeader function:

import {HttpClient} from 'aurelia-http-client';

export class Spacemoney{
  static inject() { return [HttpClient]; }

  constructor(http) {
    this.env = 'development';
    this.apiToken = '...';
    this.http = http.request.withHeader('Authorization', 'Token token="' + this.apiToken + '"');
  }
  ...
}

When the request is made, no Authorization header is set. Let me know if there's any more information I can provide that would help.

BTW, I have been building a sideproject using Aurelia for the past 72 hours, and I am in love. I'm so excited to see this project mature!

Can't set X-ZUMO-APPLICATION in request header

I am creating an Aurelia web project that will consume an API. The API is housed as an Azure Mobile Service. I know I need to add the X-ZUMO Auth header to the request. But, when I instantiate my http client, that header never makes it to the request headers according to the browser dev tools.When I run this in my application, I am presented with a login screen I presume because the X-ZUMO header is not present so the app doesn't have permissions to run. I am running this using gulp which is setting up a local instance of the web application for me. I also tried the external IP address.

I'd love to use Aurelia for this new project, but if I can't get past this point I'll need to go to something else.

Here is my web api class:

import {HttpClient} from 'aurelia-http-client';

export class WebApi
{
static inject = [HttpClient];
constructor(http)
{
    this.http = http;
    this.baseUrl = 'https://myProject.azure-mobile.net/';
    this.zumoHeader = 'X-ZUMO-APPLICATION';
    this.zumoKey = 'zumoKey';
    this.client = new HttpClient()
        .configure(x => {
        x.withBaseUrl(this.baseUrl);
        x.withHeader(this.zumoHeader, this.zumoKey);
    });
}

// requests will go here
testGet()
{
    this.client.jsonp('api/logs?application_id=sessionID&__count=20')
    .then(response =>
    {
        alert(response);
    });
}
} 

All POST requests being sent twice.

As far as I can tell in version 0.5.3, all of my POST requests are being sent twice. Once with the proper data I would expect (though this seems to happen silently as it is not picked up by the dev tools in browser, but it is in my api server's logs.), then a second time with the payload of nothing for all data variables. So basically, every time I post, I am seeing two separate POST requests to the api server. One that is legitimate and one that is just a garbage request with no data payload.

developer_tools_-http___localhost_9000_

an example request with empty payload

carriage_ root_carriage-api___var_www_carriage_current ssh 150x44_and_developer_tools-http___localhost_9000_

Excerpt from the api server logs showing two posts back to back, one with the data, one without.

My code is fairly straight forward:

  addOrganization(){

    var json = {
      'name': this.org_name,
    };
    return this.http.post(this.new_org_url, json).then(response => {
      var dataobj = JSON.parse(response['response']);
      if (response['statusCode'] == 201){
        console.log('Success');
      }else{
        alert("something went wrong");
      }
    });

Transforming post request to x-www-form-urlencoded format

Hi there,

Just wondering if you could provide a snippet or give some direction as to how best to transform an http.post request to a x-www-form-urlencoded format within an Aurelia application.

The API I'm consuming relies upon this format.

Cheers,
Dan

is http.put() fully functional?

I was advised (some time ago) that rather than using the defaults in

save(movie) {
        return this.http.put(baseUrl, movie);
    }

I should use the request builder to be very specific:

save(movie) {
        var request = this.http.createRequest();
        request.asPut()
               .withUrl(baseUrl)
               .withHeader("Accept", "application/json")
               .withHeader("Content-Type", "application/json")
               .withContent(movie);

        return request.send().then(response => response.content);
    }

Is this still the case? The reason for this question is that when using the first, more generic form I get

Unhandled promise rejection Error: A value is required for route parameter 'id' in route 'details'.
    at RouteRecognizer.generate (http://localhost:3000/jspm_packages/github/aurelia/[email protected]/index.js:335:17)
    at AppRouter.generate (http://localhost:3000/jspm_packages/github/aurelia/[email protected]/index.js:1053:34)
    at eval (http://localhost:3000/movies/edit.js!eval:42:53)
    at run (http://localhost:3000/jspm_packages/npm/[email protected]/modules/es6.promise.js:91:43)
    at http://localhost:3000/jspm_packages/npm/[email protected]/modules/es6.promise.js:105:11
    at module.exports (http://localhost:3000/jspm_packages/npm/[email protected]/modules/$.invoke.js:6:25)
    at queue.(anonymous function) (http://localhost:3000/jspm_packages/npm/[email protected]/modules/$.task.js:40:9)
    at Number.run (http://localhost:3000/jspm_packages/npm/[email protected]/modules/$.task.js:27:7)
    at listner (http://localhost:3000/jspm_packages/npm/[email protected]/modules/$.task.js:31:9)

Better HTTP header support

The plugin manages the HTTP header as it was just a plain { key: value } object, where HTTP RFC2616 states that header fields can appear multiple times, e.g. this could be a valid response:

HTTP/1.1 200 OK
...
X-Modified-By: <heruan>; timestamp="1436536800"
X-Modified-By: <holly>; timestamp="1438359715"

and also have a well-defined syntax: field-name: field-value[; param1="value", param2="value"], for example the Link header (e.g. used to link a JSON schema URI to a response) may appear as:
Link: <http://example.org/api/users/$schema>; rel="describedBy". Also field names should be treated case-insensitive.

Why not use a Map or a Set to store header fields in the Headers class, with methods to query and retrieve the field value separately from parameters? It would really improve the plugin.

See:

Member variable being changed during promise chain

Hi Aurelia team,

Sorry to bother you but I am really at a loss as to what is happening with this issue I have and need some input from you. I have replicated the issue in a fork of the skeleton. It is acting a little different to the issue I have, but is still changing a saved value between one "then" and the next in a promise chain.

To see the issue clone this;
https://github.com/grantcarthew/skeleton-navigation

npm/jspm install watch etc...

Open the browser, I am using Chrome, and open the dev tools.
Switch the dev tools to the console tab.
Click on the Flickr route.

Looking at the code you will see I have used the model and service design that Patrick Walters @PWKad has published on his blog. It is a really comfortable abstraction and I would like to keep using it.

The issue you will see in the console, and if you click on the Flickr.js file, is that "this.person" is being transformed from a PersonModel object into a generic object.

I have no idea why this is happening. It could be a number of things causing it. The most probable is that I have made a mistake somewhere.

I don't know how to fault find this either.

As I said, the issue you see here is slightly different to the one I have in my application. In my application the object is still a person model object, but the number values are changing to strings.

So in the first Then block, this.person = PersonModel { "thing": 123 }, then in the second Then block, this.person = PersonModel { "thing": "123" }. You will notice the quotes around the number in the second Then block.
Again, this is not what you will see in the fork of the skeleton, but it is along the same lines.

Any help is greatly appreciated,

Regards,

Grant.

HTTP failures are not getting caught

I downloaded the new version of Aurelia with [email protected] and tried to run this application skeleton

When I tried to visit the flickr page, I got a 503 error because flickr was blocked. Tried to catch the error like this:

import {HttpClient} from 'aurelia-http-client';

var url = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=rainier&tagmode=any&format=json';

export class Flickr{
  static inject() { return [HttpClient]; }
  constructor(http){
    this.heading = 'Flickr';
    this.images = [];
    this.http = http;
  }

  activate(){
    var req = this.http.jsonp(url);
    console.log(req);
    return req.catch(error => {
       // Nothing to show, just make sure the app keeps running
       this.images = [];
    }).then(response => {
      this.images = response.content.items;
    });
  }
  canDeactivate(){
    return confirm('Are you sure you want to leave?');
  }
}

but nothing happened.

After debugging the request-message-processor.js file and adding some breakpoints in all the cases where the returned promise gets rejected, I see that none of the xhr handlers gets called. So the promise never gets rejected and catch never gets called

Good practice advice request: is abstracting an httpClient request in a service class recommended?

Simple case: I have a login screen with viewmodel.
In order to keep the viewmodel focussed on it's viewmodel functionality I encapsulate the http handling in authService.js:

//authService.js
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
import {Authentication} from './authentication';

@inject(HttpClient,Authentication)
export class AuthService  {
    constructor( http, auth){
        this.http = http;
        this.auth = auth;
    }
    login(email, password){
        return  new Promise((resolve,reject)=>{
            var loginUrl = this.auth.getLoginUrl();
            return this.http.createRequest(loginUrl)
            .asPost()
            .withContent({'email': email, 'password':password})
            .send()
            .then(response => {
                this.auth.setToken(response);
                resolve(response);
            })
            .catch(err => {
                console.log("error :" + err.content.message);
                reject(err);
            });
        });
    }
}

This makes login.js more testable:

//login.js
import {AuthService} from './authService';
import {inject} from 'aurelia-framework';


@inject(AuthService )

export class Login{
    constructor(auth){
        this.auth = auth;
    };

    heading = 'Login';
    email='';
    password='';
    login(){
        this.auth.login(this.email, this.password)
        .then(response=>{
            console.log("ok logged in login.js");
        })
        .catch(err=>{
            console.log("error logged in login.js");

        });
    }
}

Simple question: is this the way to go? It works but is the promise wrapping done correctly?
thanks.

http.setRequestsHeader

I'm trying to post JSON to my api endpoint. If I make an XMLHttpRequest() it works. If I make an http-client, it doesn't.

    var data = {"image": "http://placekitten.com/200/200/?image=9", "title": "test"};

    //this works... 
    var xmlhttp = new XMLHttpRequest();   
    xmlhttp.open("POST", "/api/pin");
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.send(JSON.stringify(data));        

    //this does not - just causes the page to browsersync to refresh the page
    this.http.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    this.http.post('/api/pin', JSON.stringify(data));

Intercept calls for Testing

Angular provides a quite nice service called ngMockE2E which enables intercepting any outgoing http calls and responding with mocks.

Not only is this useful for mocking real requests for testing, but would also allow to do Backend-less Development which is a really nice thing if your Backend and Frontend team wants to adhere to agreed interfaces.

Treating JSON response as text (for IE).

I was wondering if rather than forcing all JSON typed responses to be of type text that then requires the end user to parse into json - would it be better to have a post processor for just IE and let the browser native parsing of the response work as intended. This should improve performance in chrome and firefox and all browsers who natively support json as a response type. I believe this is how jquery does it (not 100% sure).

export function responseTypeTransformer(client, processor, message, xhr){
var responseType = message.responseType;

if(responseType === 'json'){
responseType = 'text'; //IE does not support json
}

xhr.responseType = responseType;
}

How to pass object from httpclient request to interceptor?

Practical case:

  • adding an authentication token happens inside request interceptor.
  • I need a mechanism in order the exclude the token for certain request messages (the majority of request needs to include the token), so that particular request are enriched with {"skipToken": true}. The interceptor could then use skipToken in it's internal processing.

I don't see a straight-forward way to do this?
thanks.

Possible bug on http-client 0.10.1

I just upgraded to latest aurelia version. Since then, I'm getting a funky error at aurelia-http-client.js that prevents app to start.

The error text is "Super expression must either be null or a function, not undefined" and it's produced at line 359 of the http-client.js file.

Watchin the file I can see that there's a JSONPRequestMessage class at line 347 that inherits from RequestMessage, defined below in the same file at line 605. It seems that error is due because JSONPRequestMessage is defined earlier in the file than RequestMessage class. Moving RequestMessgae above in the file seems to fix the issue. Meanwhile I'm using version 0.10.0

API suggestion: replace `request` getter with `createRequest` method

I think the HttpClient.request getter is an awkward way to create a new request. The getter makes it look like it's mutating the client's state, or something. I think the API would be considerably clearer if it were a method instead.

Current API:

client.request
  .withParams({ foo: 'bar' })
  .get(uri);

Proposed API:

client.createRequest()
  .withParams({ foo: 'bar' })
  .get(uri);

Provided d.ts miss most of RequestBuilder's functions.

RequestBuilder typings are missing all the as*() and with*() functions.
I use this as a temporary workaround:

export class RequestBuilder {
    client: any;
    transformers: any;
    useJsonp: any;
    constructor(client: any);
    /**
    * Adds a user-defined request transformer to the RequestBuilder.
    *
    * @method addHelper
    * @param {String} name The name of the helper to add.
    * @param {Function} fn The helper function.
    * @chainable
    */
    static addHelper(name: any, fn: any): void;
    /**
    * Sends the request.
    *
    * @method send
    * @return {Promise} A cancellable promise object.
    */
    send(): any;
    /**
    * Missing functions
    **/
    asDelete: () => RequestBuilder;
    asGet: () => RequestBuilder;
    asHead: () => RequestBuilder;
    asOptions: () => RequestBuilder;
    asPatch: () => RequestBuilder;
    asPost: () => RequestBuilder;
    asPut: () => RequestBuilder;
    asJsonp: () => RequestBuilder;
    withUrl: (url: any) => RequestBuilder;
    withContent: (content: any) => RequestBuilder;
    withBaseUrl: (baseUrl: any) => RequestBuilder;
    withParams: (params: any) => RequestBuilder;
    withResponseType: (responseType: any) => RequestBuilder;
    withTimeout: (timeout: any) => RequestBuilder;
    withHeader: (key: any, value: any) => RequestBuilder;
    withCredentials: (value: any) => RequestBuilder;
    withReviver: (reviver: any) => RequestBuilder;
    withReplacer: (replacer: any) => RequestBuilder;
    withProgressCallback: (progressCallback: any) => RequestBuilder;
    withCallbackParameterName: (callbackParameterName: any) => RequestBuilder;
}

http-client 0.10.2 missing index.js file: causing undefined error on import

When I try to import the http-client in code, with version 0.10.2, I get an error saying that the HttpClient is undefined. I believe this is because the index.js file is missing from the src directory. Can someone help to confirm this? I want to see if others are running into the same issue before I issue a pull request for this.

The returned promise from send isn't cancellable

As the documentation states

/**

  • Sends a message using the underlying networking stack.
    *
  • @method send
  • @param message A configured HttpRequestMessage or JSONPRequestMessage.
  • @param {Array} transformers A collection of transformers to apply to the HTTP request.
  • @return {Promise} A cancellable promise object.
    */

It should return a cancellable promise object which it doesn't since it's added on the wrong promise object. Also not sure but maybe it should be rejected also.

Add detection of common response headers

Add detection of common response headers and set the responseType accordingly.
The .content getter should then always return the proper format according to the responseType.
The raw content can always be retrieved with .response property

HttpResponseMessage is hard to use.

https://github.com/aurelia/http-client/blob/master/src/http-response-message.js#L34-L61

It is difficult to write robust code when methods behave like this one. In particular, the part where it parses the json for you if the content-type is json. In my code, I have to now check the content type and branch according to it. This is especially true if running static analysis (TypeScript) since content can return either an object or a string.

I would prefer it if there were two methods, one for getting the raw content and another for getting the parsed content. For backwards compatibility reasons, I suppose this means two methods added: contentAsString and contentAsObject.

  • contentAsString would only return me string content, regardless of the content-type.
  • contentAsObject would only return me a deserialized JSON object if the content-type was json, it would throw in all other cases.

In general, it is pretty rare that someone doesn't know the content-type of the request they are processing so it is likely that the most desired behavior is a thrown error if the content isn't of the appropriate type (e.g., they get non-JSON when they asked for JSON).

Track outstanding http calls

It would be nice if we had a way in the client to know if there are some outstanding request. This could be quite helpful in combination with E2E tests (as mentioned here aurelia/framework#12) so we start testing only when the initial work is really done, including any http calls during initial page creation

Parameters

I have noticed, that you can call client.get(url) or other methods. Usually what you do is, that you have some parameters for the GET request or other methods. It would be nice to be able use them directly from client. E.g.:

this.client.get('some/cool/url', { q: 'foo' });

instead:

this.client.createRequest('some/cool/url').asGet().withParams({ q: 'foo' }).send();

Also this should be available for POST, PUT, PATCH, HEAD, DELETE methods.

For PUT, PATCH and POST this will be a breaking change, but I think it is very useful.

How can I determine whether the HttpClient is loading?

I'd like to bind the nav-bar spinner such that route-navigating or http loading triggers the spinner.

I'm hoping I can inject the HttpClient and read some property. But I can't see anything..

Am I missing something, or is this functionality not present?

Something like $.ajaxPrefilter()

Hi guys, this is more a feature request than an issue.

I'd love a way of being able to sanely filter request responses in a similar way to jQuery.ajaxPrefilter(). The use case is looking for things like 401s and determining login state on each request - is there currently a hook for doing this I'm unaware of? The only way I'm aware of is wrapping the request methods in some way, which seems a bit ugly.

Thoughts?

Thanks ❤️

always resolve with instance of HttpResponseMessage

I'm doing some testing with the http-client as I work on the breeze ajax adapter. In situations where the xhr.onerror event occurs the http client is rejecting the promise with instance of the Error class. What do you think about letting it resolve with an instance of HttpResponseMessage? Same thing goes for the ontimeout event.

here's an example- in this case I'm debugging a dropped request. In the watch window you can see the HttpResponseMessage I newed up to see if it would work:
debugger

My reasoning here is send resolves in the case of 400/500/etc, might as well resolve in statusCode=0 type situations.

Unattaching interceptors

It must be possible to unattach interceptors from a client. I see two ways to allow that:

  1. Keep some data about each transformer in the transformers array, to allow finding and removing a transformer without calling it.
  2. Move transformers out of the request builder and handle them seperately. They were just moved there though, so i assume there is a good reason for them to be there.

I think option 1 is better, because then it will also be possible to remove transformers that modify the same property:

client.configure(x => {
  x.asGet(); // unnessecary to call
  x.asDelete();
}

What do you say?

IE11 - POST sending "undefined" string in body instead of empty string when no second param is passed to post

Configuration

        this.http = http.configure(x => {
            x.withHeader('Content-Type', 'application/json');
            x.withCredentials(true);
        });

When you call post like this:

    this.http.post('http://somehost/someservice');

In chrome, it will send an empty body. This is what would be expected for a JSON post with no request object.

In IE 11, however, it sends a body containing the string "undefined." This is not expected behavior and tends to fail as the bare string "undefined" is not valid json.

The current workaround, is to explicitly pass the request object as null, which will work in both IE and chrome:

    this.http.post('http://somehost/someservice', null);

Authentication

Hi,

Using xmlhttprequest I can send user credential (username and password) using open method overload " open(method, url [, async = true [, username = null [, password = null]]])"
how can I send user credentials with aurelia-http-client?

thanks in advance

"repeat.for" construct fails as a function of http-client data source

This is weird and I hope is not a silly pilot error. I have a simple pair {app.js, app.html} defined as

import {HttpClient} from "aurelia-http-client";

export class App {

    constructor () {
        this.http = new HttpClient();
    }

    activate() {
        return this.http.get("/api/movies")
                        .then (response => {
                            this.movies = response.content;
                        });
    }

}

and

<template>

    <div class="container">

        <div> You have ${movies.length} movies.</div>

        <table class="table">
            <tr>
                <th>Title</th>
                <th>Year</th>
            </tr>
            <tr repeat.for="movie of movies">
                <td>${movie.title}</td>
                <td>${movie.releaseYear}</td>
            </tr>
        </table>
    </div>

</template>

here is the screenshot of the Chrome debugger in action

image

which indicates that the http.get() method fetched the correct content. The app.html renders the view shown below:

image

Note that ${movies.length} correctly evaluates to 3 - while the loop repeat.for="movie of movies" gets executed 0 times.

What is really weird is that replacing the http.get("/api/movies") with http.get("/movies.json") which is the reference to the file in the client's root folder as shown below

image

without any other changes in this project results with what one would expect:

image

Http interceptor

I would like to have some sort of mechanism to intercept certain responses.
If my httpClient receives a 401 f.ex., I want to redirect my user to a certain page.

Add Accept header by default set to application/json

We had an issue when Firefox was sending http request it sets the following Accept header:
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
And that makes WebAPI to default to XML formatter for response.

Chrome and IE just send */* and json is rendered by default.

Setting Accept to 'application/json' should provide uniformity between the browsers.

Consider dropping or using the fetch polyfill

I like what I've seen of Aurelia, but I was surprised with such a forward focus that you still have a http module.

given the new fetch standard (implemented in chrome today, firefox very soon - http://caniuse.com/#feat=fetch) and fetch polyfill - https://github.com/github/fetch, would it be better to either abandon this part of Aurelia or if it does provide functionality over fetch (sorry, have only looked at the basic features) then base this on top of fetch instead of XmlHttpRequest ?

API suggestion: allow RequestBuilder to specify URI, method, and content without sending the request

I think RequestBuilder's API should be optimized for building requests, and not necessarily sending them. Currently the methods used to specify the URI, HTTP method, and request body/content also send the request, making it impossible to build a request without sending it. It should be possible to use this class to build a complete request and still maintain control over when it's sent.

I also think the semantics of these methods are a little unclear. Consider the code,

httpClient.createRequest()
    .post(uri, content)

Asking a request to post something doesn't make sense because "post" is a property or attribute of a request. It's something a client does, not something a request does. It makes more sense to tell the request that it uses "post", and then ask for the request to be sent.

I propose the following changes to the RequestBuilder class:

  • Replace .get(), .post(), etc. methods with .with- style methods that specify the HTTP method with no side effect.
  • Add .withUri() and .withContent().
  • Add a .getRequest() method that returns a complete HttpRequestMessage.
  • Add a .send() convenience method to let the API stay fluent and chain-able.

We could also consider allowing the URI and HTTP method to be passed as parameters to HttpClient.createRequest().

Current API:

client.createRequest()
    .withParams({ foo: 'bar' })
    .get('/cool/stuff');

client.createRequest()
    .withParams({ foo: 'bar' })
    .post('/cool/stuff', { some: 'content' });

Proposed API:

client.createRequest('/cool/stuff') // or `.withUri('/cool/stuff')`
    .withGetMethod() // it seems reasonable to make GET the default, and allow this to be omitted
    .withParams({ foo: 'bar' })
    .send();

client.createRequest('/cool/stuff')
    .withPostMethod() // or .withMethod('POST')
    .withContent({ some: 'content' })
    .send();

Cannot install with npm

I am trying to use aurelia-http-client commonjs dist through npm (not an aurelia.io app, bundled with browserify):

 $ npm install --save aurelia-http-client

but get the following error:

npm ERR! 404 404 Not Found: aurelia-http-client
npm ERR! 404
npm ERR! 404 'aurelia-http-client' is not in the npm registry.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.