跨域请求被阻止:在Angular2发布请求中向laravel发送标头时出现问题

时间:2016-12-02 14:24:03

标签: php angular laravel-5 http-headers cross-domain

我正在使用angular2 + laravel,我正在尝试使用 headers 发布请求,但是它给出了 Cross-Origin Request Blocked:错误。如果任何机构知道如何解决它。

我做了一些可能的解决方案,例如在laravel的htaccess文件中启用Access-Control-Allow-Origin“*”并创建了CORS中间件,但这些解决方案无效。这是我的角度代码。

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import configApp = require('../_configs/app.settings');
//import '../assets/frontend/custom/js/jquery.toaster.config.js';
declare function maketoast(status: string, message: string) : void;


@Injectable()
export class ForgotpasswordService {

constructor(private http: Http) { }

forgotPassword(email: string, token: string) {

    alert(token)
    var headers = new Headers();

   // headers.append('Content-Type', 'application11/json');

    let headers = new Headers();
    headers.append("Authorization", "Bearer " + token;
    let options = new RequestOptions({ headers: headers });

    // console.log(configApp.apiUrl+/test);
    return this.http.post(configApp.apiUrl+"/password/email", JSON.stringify({ email: email, apiRequest:1}), options } )
        .map((response: Response) => {

            // login successful if there's a jwt token in the response
            let user = response.json();

            console.log(user.status);
            if(user.status == false){

                maketoast(user.toaster_status, user.message);
                event.stopImmediatePropagation;
                event.preventDefault();
                event.stopPropagation();

            }


            if (user.status == true) {

                maketoast(user.toaster_status, user.message);

            }
        });

}

resetPassword(token: string, email: string, password: string,     confirmPassword: string) {


    // console.log(configApp.apiUrl+/test);
    return this.http.post(configApp.apiUrl+"/password/reset",   JSON.stringify({ token: token, email: email, password: confirmPassword, confirmPassword: password, apiRequest:1}))
        .map((response: Response) => {

            // login successful if there's a jwt token in the response
            let user = response.json();

            console.log(user.status);
            if(user.status == false){

                maketoast(user.toaster_status, user.message);
                event.stopImmediatePropagation;
                event.preventDefault();
                event.stopPropagation();

            }


            if (user.status == true) {

                maketoast(user.toaster_status, user.message);

            }
        });

}

}

2 个答案:

答案 0 :(得分:0)

这是服务器端问题。

创建中间件:

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

并添加到您的路线:

Route::group(['middleware' => ['cors']], function () {

//您的路线代码     });

答案 1 :(得分:0)

我使用laravel和angular 2。

在Laravel上我安装了模块barryvdh / laravel-cors,当我进行POST调用时,标题包括Access-Control-Allow-Origin" *"。

但是angular2在POST之前使用OPTIONS进行预检,而且Laravel没有发送Access-Control-Allow-Origin" *"当行动是OPTION。

所以,我把它添加到.htacess文件

RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-   Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"