带有管腔的Angular2在请求的资源上存在无访问控制 - 允许原始标头



我正在尝试创建API,该API在前端2应用程序和后端腔5.4上具有。

我已经处理了get请求,并且它运行得很好,现在我对发布请求有问题。

在前端我使用类似的东西

this.headers.append('Access-Control-Allow-Origin', '*');
    return this.http
        .post(`${this.url}${this.createAction}`,JSON.stringify({name: name, lead: lead}), this.headers)
        .toPromise()
        .then(response => response.json().code)
        .catch(this.handleError)

,在后端我的方法看起来像这样

public function createAction(Request $request)
{
    $this->parseData($request->all());
    $character = new Character();
    $character->name = $this->name;
    $character->lead = $this->lead;
    try {
        $character->save();
    } catch (Exception $e) {
        return response()->json(['code' => $e->getCode(), 'message' => $e->getMessage()]);
    }
    return response()->json(['code' => '200', 'message' => 'ok']);
}

所以我尝试使用

https://gist.github.com/danharper/06d2386f0b826b669552 https://github.com/neomerx/cors-illuminate https://gist.github.com/ardani/168015BE6E0F789F0E09EFC10CE54810

我还尝试从两侧手动发送标头,但我仍然有同样的错误:

xmlhttprequest无法加载http://localhost/angularjs/laravelWithAngular2App/lumen_backend/public/create/。从'http://localhost/angularjs/laravelWithAngular2App/lumen_backend/public/create/'转到'http://localhost/create'已被CORS策略阻止在请求的资源上。源'http://localhost:3000'不允许访问。

那么,我在做什么错,为什么当我不重新定向时我有类似重定向的东西?

P.S

变量名称和铅位于前端,路线是正确的

要克服CORS策略的问题:无'access-control-wall-allow-Origin': -

  1. 首先,您需要创建一个中间件" Corsmiddleware.php"
public function handle($request, Closure $next){
    $headers = [
       'Access-Control-Allow-Origin'  => '*',
       'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
       'Access-Control-Allow-Credentials'=> 'true',
       'Access-Control-Max-Age'          => '86400',
       'Access-Control-Allow-Headers'=> 'Content-Type, Authorization, X-Requested-With'];    
    if ($request->isMethod('OPTIONS'))
    {
        return response()->json('OK', 200, $headers);
    }    
    $response = $next($request);
    foreach($headers as $key => $value)
    {
        $response->header($key, $value);
    }    
    return $response;
}

并在corsmiddleware.php

中添加上面的代码
  1. 现在,您必须在App http kernel.php

    中注册中间件

    保护$ middleware = [ ... app http middleware corsmiddleware :: class,];

我希望它对您有帮助。

最新更新