0

I'm leaning Angular, trying to use HTTP get to a file on my PC. I want to simulate the server scenario so tried serving the file with the following, (live-server, browser-sync & xampp) one at a time, but with every try I get the error

Failed to load http://localhost/ng-data/products.json: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:4200/' that is not equal to the supplied origin. Origin 'http://localhost:4200' is therefore not allowed access

When I paste the url (http://localhost/ng-data/products.json) in my browser I can get the file.

halfer
  • 19,824
  • 17
  • 99
  • 186
shireef khatab
  • 977
  • 2
  • 13
  • 33

2 Answers2

2

I found other 2 ways to work around this situation,

solution 1:

To change the products.json file to products.php, then add this at the top:

<?php  
  'header(Access-Control-Allow-Origin: *)';
  'header(Content-Type: application/json)'
?>  

finally, change the url which you are connecting to, from products.json to products.php

solution 2

using proxy configuration see: Angular documentatiom

follow these steps:

1- change the url inside the service to '/api/products' instead of 'http://localhost/products'

2- create proxy.config.json file in the root directory of your angular project add this code inside it:

    {
  "/api/*": {
    "target": "http://localhost",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

3- create folder api on the server and add the products.json inside it.

Note: in my case i'm using localhost with no port specified as i'm using xampp. but if ur using node for example you will specify the port like: localhost:3000 in proxy.config.json

shireef khatab
  • 977
  • 2
  • 13
  • 33
-3

Because you're testing, I suggest you use the Chrome extension. Please search this in the Chrome extension list as shown below and then enable it. Probably your problem will be solved.

enter image description here

BehrouzMoslem
  • 9,053
  • 3
  • 27
  • 34