0

Error: Access to XMLHttpRequest at 'myserviceURL' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Sample Code:

  let myHeaders = new HttpHeaders();
  let username: string = 'admin';
  let password: string = 'admin';
  myHeaders.append("Authorization", "Basic " + btoa(username + ":" + password));
  myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');

  var data={
        "username":userName,
        "password":Password,
  }

  return this.http.post(url, data, { headers: myHeaders })
  .subscribe(
  res =>{
    console.log(res);
  },
  err => {
    console.log("Error occured "+err.status);
  }
  );
2
  • How's the backend code? When you do a request, have you added http:// at the start? Commented Feb 27, 2019 at 12:55
  • 2
    To you have access to the server? CORS is a server side setting so it won't be a client side problem. Commented Feb 27, 2019 at 12:56

3 Answers 3

1

If your back-end is running on different port, Chrome, by default, will prevent Cross origin resource sharing. When you are developing app, you have to create proxy that will be ran within ng serve or npm start and he will recreate/forward all your api calls to specified address. Here's example:

//proxy.json

   {
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

What does this mean? Any http request that is pointed towards /api will be rewritten to http://localhost:8080.

Also, you have to either change npm start property inside of package.json or change ng serve inside of angular.json so that proxy will be ran by default with command ng serve/npm start

//angular.json

"serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "yourapp:build",
        "proxyConfig": "proxy.json"
      },
      "configurations": {
        "production": {
          "browserTarget": "yourapp:build:production"
        }
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

As it is a server-side issue, What you can do is: If you are using chrome, you can add chrome extension for CORS which will allow access to 'Access-Control-Allow-Origin'

it will work.

worked for me!!!

Comments

0

when you are using 'application/x-www-form-urlencoded' Please send the encoded data(Object) in this format.

    const data =
      'username=' +
      encodeURIComponent(userName) +
      '&password=' +
      Password +
      '&grant_type=password';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.