DZN
DZN

Reputation: 1553

Angular2/NodeJS: Can not get data from the backend on localhost

I've written a small SPA app using Angular 2 on the frontend & NodeJS for the backend

I started both backend & frontend on my computer (http://localhost:3000 & http://localhost:4200)

When Angular tries to get data from backend rises an error:

XMLHttpRequest cannot load http://localhost:3000/mailboxes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

EXCEPTION: Uncaught (in promise): 0 - {"isTrusted":true} ...

How to make this work?

Upvotes: 0

Views: 241

Answers (1)

Lwazi Prusent
Lwazi Prusent

Reputation: 192

Your service and client are running on 2 different ports so as far as you service is concerned, this request is coming form a foreign location. So you need to let your service side know that you are allowing this request.

To do this you need to enable cross origin resource sharing on your service https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Here is the link to an npm cors library very easy to use https://www.google.co.za/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=npm+cors

Upvotes: 1

Related Questions