Angular 2和Slim 3 Cros错误

时间:2017-01-05 22:24:58

标签: angular slim-3

我正在尝试将一些Angular 2前端与Slim 3 PHP后端集成。我有以下Angular 2服务:

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());
    }
}

我在此组件中使用此服务:

  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")
            );
    }

}

每当我想要为新用户创建一个c时,都会收到以下错误。

enter image description here

我的API看起来像这样:

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;
        }

似乎有什么问题?谢谢!

1 个答案:

答案 0 :(得分:0)

因为后端的响应中没有Access-Control-Allow-Origin标头,并且请求的域(localhost:4200)与后端的域不同( localhost:8080),Chrome自动拒绝请求。您需要将 Access-Control-Allow-Origin:localhost:4200 标头添加到后端的响应中。 Google CORS了解更多信息。