I have a Laravel API which is now allowing a new Angular2 application I am building to have access to itself. I get the following error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3073' is therefore not allowed access. The response had HTTP status code 404.
This is confusing me quite a bit as I already have two applications (one also an Angular2) application that is communicating with the API fine with no issues whatsoever. I have also created CORS middleware in the API which provides the appropriate headers to allows these applications through.
CORS Middleware
<?php
namespace App\Http\Middleware;
use Closure;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
class CORS {
public function handle($request, Closure $next) {
header("Access-Control-Allow-Origin: *");
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
My Angular2 application is attempting to call my API using this code:
import { Injectable } from "@angular/core";
import { Http, Headers, RequestOptions } from "@angular/http";
import { Observable } from "rxjs";
@Injectable()
export class AuthService {
constructor(private _http: Http) {
}
login(loginDetails):Observable {
let body = JSON.stringify(loginDetails);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://#####-brain.dev/api/v1', body, options)
.map(res => res.json());
}
}
Does anyone have any advice as to why this particular application is not receiving the Access-Control-Allow-Origin header header? I have put a breakpoint within my CORS middleware and it doesn't hit it at all which is bizarre as it is calling exactly the same endpoint that my other application is and that is working fine.
I have also noticed that it is only POST requests that it doesn't allow through.
Thanks!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire