1
votes

when i want to add a form with API Symfony and angular js (Frontend) i had this error can someone know why ?

Failed to load http://127.0.0.1:8000/api/users: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. AddUserComponent.html:16 ERROR Error: Error trying to diff 'server error'. Only arrays and iterables are allowed at DefaultIterableDiffer.webpackJsonp.../../../core/@angular/core.es5.js.DefaultIterableDiffer.diff (core.es5.js:6843) at NgForOf.webpackJsonp.../../../common/@angular/common.es5.js.NgForOf.ngDoCheck (common.es5.js:1691) at checkAndUpdateDirectiveInline (core.es5.js:10846) at checkAndUpdateNodeInline (core.es5.js:12341) at checkAndUpdateNode (core.es5.js:12284) at debugCheckAndUpdateNode (core.es5.js:13141) at debugCheckDirectivesFn (core.es5.js:13082) at Object.eval [as updateDirectives] (AddUserComponent.html:21) at Object.debugUpdateDirectives [as updateDirec

Userservice

 @Injectable()
    export class UserService {
      private uri= 'http://127.0.0.1:8000/api/users';
      constructor(private http: Http, private authenticationService: AuthService  
     ) {}
      addUser(user: User) {
            const  headers = new Headers();
            headers.append('content-type', 'application/json');
            headers.append('Authorization', 'Bearer ' + this.authenticationService.token);
            return this.http.post(this.uri, JSON.stringify(user), {headers : headers})
            .map(res => res.json()).catch(this.handelError);
          }
2
Research "CORS", and gain some understanding. It's very important to control cross site scripting attacks.Daniel Farrell

2 Answers

1
votes

This is CORS issue. CORS is security implemented in browser.If you are using angular you can resolved this issue by creating a proxy.conf.json file to act as a proxy server.

{
  "/api*": {
    "target": "http://127.0.0.1:8000",

  },
    "changeOrigin": true
  }
}

And then modify the npm start command in package.json as below

"start": "ng serve --proxy-config proxy.conf.json"

You can read more about this on this link

0
votes

This is CORS issue. CORS is security implemented in browser.

It means that you are not allowed to make HTTP request to other domain or port than yours.

In your case your application is running on localhost:4200 but you are requesting from localhost:8000. Therefore this is blocked by browser.

For developing purposes you can use angular-cli proxy which allows you to make a tunnel on 4200 port.

For production use you should either whitelist your server in CORS security headers or make your API available on the same host (like mapping /api to your backend).