Angular 2 + Laravel API EXCEPTION:未捕获(在承诺中):响应状态:0表示URL:null

时间:2017-02-21 06:18:52

标签: angular laravel-5 http-post backend

在我的angular 2应用程序中,我写了一个简单的帖子请求,它始终返回此错误:

EXCEPTION: Uncaught (in promise): Response with status: 0  for URL: null

经过一些搜索后我发现它可能是一个CORS问题,所以我在我的API后端实现了一个CORS类:

使用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);
    }
}

我还尝试为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');

在我的其他项目中,此配置工作正常,但对于新项目总是会收到此错误。

Angular 2代码:

sendSingleMail(){

  var headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  var creds = "data";

  this.http
  .post("http://api.mailer.dev/sendSingleEmail", 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);
}

我也试过使用不同的标题,但没有结果。有没有人有这个问题?有什么建议可以解决吗?

0 个答案:

没有答案