In my angular 2 app, I wrote a simple post request which always returns this error:
EXCEPTION: Uncaught (in promise): Response with status: 0 for URL: null
After some search I found that it might be a CORS issue, so I've implemented a CORS class on my API backend:
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : false;
$allowed_origins = ['http://sub.example.com' , 'http://localhost', 'http://localhost:4200', 'http://localhost:3000'];
if(in_array($http_origin, $allowed_origins)) {
return $next($request)->header('Access-Control-Allow-Origin' , '*')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
}
return $next($request);
}
}
Also what I tried is to add additional route for OPTIONS:
Route::options('{all}', function () {
$response = Response::make('');
if(!empty($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], ['http://localhost:4200'])) {
$response->header('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']);
} else {
$response->header('Access-Control-Allow-Origin', url()->current());
}
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization');
$response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header('X-Content-Type-Options', 'nosniff');
return $response;
});
Route::options('{all}', 'HomeController@options')->where('all', '.*');
//JWT AUTHENTIFICATION
Route::group(['middleware' => 'cors'], function () {
//if throws CORS error - put all routes in this cors middleware group
/* MAILER ROUTES */
Route::post('/sendSingleEmail', 'HomeController@sendSingleEmail');
On my other project, this configuration works pretty fine, but for new project always receive this error.
Angular 2 Code:
sendSingleMail() {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
var creds = "data";
this.http
.post("http://ift.tt/2lBdbdg", JSON.stringify(creds))
.toPromise()
.then(res => console.log(res))//res.json().data)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
I've also tried to use different headers but no result. Does anybody else have this issue ? Any suggestions how to solve ?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2m6H17g
via IFTTT
Aucun commentaire:
Enregistrer un commentaire