【问题标题】:Access to XMLHttpRequest has been blocked by CORS policy. No 'Access-Control-Allow-Origin' header is present on the requested resourceCORS 策略已阻止对 XMLHttpRequest 的访问。请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2020-01-30 21:43:37
【问题描述】:

当我尝试通过 api 发送电子邮件时,我收到以下消息:

从源“https://urosciric.com”访问“https://api.urosciric.com/mail”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。

我见过很多解决方案,其中没有一个是相同的,到目前为止都没有一个有效的解决方案。

角度代码:

    const httpOptions = {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
      })
    };

    this.http.post('https://api.urosciric.com/mail',
      { firstName: this.FirstName, lastName: this.LastName, email: this.Email, phone: this.Phone, text: this.Text },
      httpOptions)
      .pipe(catchError(err => {
        this.onMailSend(false);
        return throwError(err);
      })).subscribe(data => {
        this.onMailSend(true);
        return data;
      });

Laravel (api) 代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

use App\Mail\General;

class MailController extends Controller
{
    public function send(Request $request){

            $firstName = $request -> input('firstName');
            $lastName = $request -> input('lastName');
            $email = $request -> input('email');
            $text = $request -> input('text');
            $phone = $request -> input('phone');

            $to = "ciricbgd@gmail.com";
            $subject = "[urosciric.com] email from ".$firstName." ".$lastName;
            $txt = $text;
            $headers = "From: mail@urosciric.com";

            mail($to,$subject,$txt,$headers);

            return response()->json('Mail sent. Thank you!', 201); 

        return response()->json('Mail not sent. Please try contacting me directly at ciricbgd@gmail.com',400);
    }
}

当我尝试开发或生产模式时,我收到此错误, 但是当我使用 postman 或 api 测试软件时,一切正常。

【问题讨论】:

标签: angular laravel http


【解决方案1】:

您需要创建一个proxy.conf.json 文件并将这些属性添加到其中

{
"/": {
                "target": "http://api.urosciric.com/mail",
                "secure": false,
                "logLevel": "debug"
  }
}

那么您必须将此文件添加到options 下的angular.json,其路径如下

"serve": {
 "options": {
        "browserTarget": "app:build",
        "proxyConfig": "src/proxy.conf.json"
      },
   }

这对我有用,希望对你有用

【讨论】:

  • 还是一样:/
  • 尝试将 url 路径更改为 http 而不是 https 只是为了检查它是否可以工作。
  • 确保在ng serve之前运行ng build
  • 还是没有,同样的问题
【解决方案2】:

首先,您必须了解处理请求的 CORS 策略响应,后端/API 始终负责。因此,对 Angular 前端的任何添加都无济于事

其次,简单来说,大多数浏览器都有 CORS 策略来强制防止与 CSRF 攻击相关的问题。因此,如果您使用 隐身模式 访问它不会给您 CORS 错误。此外,当您使用 POSTMAN 或其他 API 测试软件 时,它们只是 开发者工具,而不是浏览器,因此它们并不关心CORS

至于解决方案,您需要创建一个全局中间件来处理这个 CORS 问题。

如果你使用 Laravel API MicroFramework Lumen -

中间件handle():

public function handle($request, \Closure $next)
{
    $headers = [
        'Access-Control-Allow-Origin'      => '*',
        'Access-Control-Allow-Methods'     => 'GET, POST, PUT, PATCH, OPTIONS, DELETE',
        'Access-Control-Allow-Headers'     => 'Accept, Content-Type, Origin, Authorization, X-Requested-With, Content-Language, Subject'
    ];

    if ($request->isMethod('OPTIONS'))
    {
        return response()->json('{"method":"OPTIONS"}', 200, $headers);
    }

    $response = $next($request);

    foreach($headers as $key => $value)
    {
        $response->header($key, $value);
    }

    return $response;
}

然后,在bootstrap/app.php注册这个中间件就可以工作了:

$app->middleware([
   ...
   App\Http\Middleware\CorsMiddleware::class,
]);

因此,当任何请求到达您的 API 时,它将通过此​​中间件并被验证为有效请求。

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 2020-06-24
    • 2020-10-11
    • 2020-08-30
    • 2021-06-30
    • 2023-04-07
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多