自昨天以来,我一直在尝试启用php中的cors来使用angular的api。我使用的是Slim和tuupola / cors-middleware库,我按照说明进行操作,但是对我来说不起作用,我无法发表帖子,并且我已经尝试了不同的方法。
这是我的代码: 苗条的中间件配置:
$app->add(new Tuupola\Middleware\CorsMiddleware([
"origin" => ["*"],
"methods" => ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
"headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"],
"headers.expose" => ["Etag"],
"credentials" => false,
"cache" => 0
]));
苗条的控制器响应:
return $response->withJson(
[
'success' => [
'message' => $signInUserResponse->message()
]
],
200
);
Angular 6通话代码:
export class UserService {
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'Application/json',
'Access-Control-Allow-Origin':'*'
})
};
selectedUser: User;
readonly URL_API = 'http://localhost:8000/signup';
users: User[];
constructor(
private http: HttpClient,
){
this.selectedUser = new User;
}
postUser(user: User){
return this.http.post(this.URL_API, user, this.httpOptions);
}
getUser(){
return this.http.get(this.URL_API);
}
}
这是错误:
Access to XMLHttpRequest at 'http://localhost:8000/signup' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.