Angular 2 and Slim 3 Cros error

316 views Asked by At

I am curently trying to integrate some Angular 2 frontend with Slim 3 PHP backend. I have the following Angular 2 service:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {

    constructor(
        private http: Http
    ) { }

    create(user: any) {
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        let options = new RequestOptions({ headers: headers });
        return this.http.post('http://localhost:8080/public/auth/signup', user, {headers: headers})
            .map(res => res.json());
    }
}

I use this service in this component:

  import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../user.service';

@Component({
    selector: 'app-signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.css'],
    providers: [UserService]
})
export class SignupComponent implements OnInit {

    model: any = { };
    postData: any;

    constructor(
        private router: Router,
        private userService: UserService,
    ) { }

    ngOnInit() {
    }

    register() {
        this.userService.create(this.model)
            .subscribe(
                data => this.postData = JSON.stringify(data),
                error => alert(error),
                () => console.log("Finished")
            );
    }

}

Everytime when i want to crate a new user a receive the following cros error.

enter image description here

My API it looks like this:

public function postSignUp($request,$response)
        {

            $validation = $this->validator->validate($request, [
                'full_name' => v::notEmpty()->alpha(),
                'email' => v::noWhitespace()->notEmpty()->email()->EmailAvailable(),
                'password' => v::noWhitespace()->notEmpty(),
            ]);

            if($validation->failed()) {
                return $response;
            }

            $new_user = $this->db->insert("users", [
                "full_name" => $request->getParam('full_name'),
                "email" => $request->getParam('email'),
                "password" => password_hash($request->getParam('password'), PASSWORD_DEFAULT),
            ]);

            $this->flash->addMessage('info', 'You have been signed up!');

            $auth = $this->auth->attempt(
                $request->getParam('email'),
                $request->getParam('password')
            );

            echo json_encode($new_user);
            return $response;
        }

What seems to be the problem? Thank you!

1

There are 1 answers

1
Mezo Istvan On BEST ANSWER

Because there is no Access-Control-Allow-Origin header is present on the backend's response, and the request's domain (localhost:4200) is different than the backend's domain (localhost:8080), Chrome automatically declines the request. You need to add the Access-Control-Allow-Origin: localhost:4200 header to the backend's response. Google CORS for more info.