Wim Verhavert Wim Verhavert - 4 years ago 243
HTTP Question

Connecting Aurelia with backend API

Context: I'm starting a new project for my company. It's been many years since I've done some web development and decided to build it using the latest platforms (so I'm a still new to all of this).

Current stack:


  • Aurelia frontend (running on localhost:9000)

  • Backend REST API using ExpressJS (running on localhost:8000)

  • PostGreSQL database running on AWS, providing data for the backend



Question: I can't seem to connect my frontend with my backend properly.

Here is my code:

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

@inject(HttpClient)
export class Login {

constructor(httpClient){
this.http = httpClient;
}

signIn() {

const url = 'http://localhost:8000/api/user/demo/test';

this.http
.get(url)
.then(data => {
console.log("data");
console.log(data);
})
.catch(error => {
console.log('Error getting ' + url);
console.log(error);
});
};

}


This always end up in the catch block, with a "response: ProgressEvent"

If I put the url in the browser I get a proper JSON:

{"status":"success","data":[],"message":"Retrieved ALL users"}


The code above only works for 'local' content, i.e. localhost:9000. As soon as I need content from somewhere else I get this error. What am I missing?

Answer Source

I think that CORS is not allowing you to access localhost:8000 from localhost:9000. To solve this, you should enable your ExpressJS server to accept CORS requests from localhost:9000 (or all hosts using a wildcard "*").

Look into these resources:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download