PHP中的CORS问题:预检请求的响应未通过。允许来源
P粉564192131
P粉564192131 2023-10-21 09:35:29
0
2
621

所以我知道那里有很多 CORS 帖子,我只是添加它们,但我找不到任何可以帮助我的答案。所以我正在构建一个依赖于我的 php api 的 Angular 4 应用程序。在本地工作没问题,当我将其与位于 app.example.com 的应用程序和位于 api.example.com 的 api 一起扔到域上时,我无法通过我的登录,因为我得到出现以下错误:

XMLHttpRequest 无法加载 http://api.example.com/Account/Login。 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许来源“http://app.example.com” 访问。

我的 php 代码如下所示:

$http_origin = $_SERVER['HTTP_ORIGIN'];

$allowed_domains = array(
    'http://example.com',
    'https://example.com',
    'http://app.example.com',
    'https://app.example.com',
    'http://www.example.com',
    'https://www.example.com'
);

if (in_array(strtolower($http_origin), $allowed_domains))
{  
    // header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Origin: $http_origin");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");
    exit(0);
}

我的 Angular 帖子如下所示:

public login(login: Login): Observable<LoginResponse> {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Authorization', 'Basic ' + btoa(login.Username + ':' + login.Password));
    return  this.http.post(this.apiBaseUrl + '/Account/Login', "grant_type=client_credentials", { headers: headers })
        .map(response => {
            // code
        });
}

如果我通过邮递员运行请求(这不会影响 CORS),我会得到:

{ "error": "invalid_client", "error_description": "Client credentials were not found in the headers or body" }

我尝试将 origin 设置为 '*' 只是为了测试并查看这是否是问题的核心,但它仍然以同样的方式失败。

编辑 只是根据以下信息进行更新。更改标头中的大小写没有任何效果,并且从 if 语句中提取代码也没有任何效果。

我通过告诉我的实时应用程序转到本地 api 来调试 php,并且 php 正在按预期工作。它设置标头并将其放入每个 if 语句中。

编辑镜头 2 我确实需要一些帮助,如果有人有任何想法,我将非常感激。

编辑镜头 3 如果我在 .htaccess 而不是 php 中设置所有标头内容,它就会让我通过。但是,现在我陷入了上面列出的错误,这是我在使用邮递员时总是遇到的错误,但现在是在使用实际网站时遇到的错误。

{"error":"invalid_client","error_description":"在标头或正文中找不到客户端凭据"}

我的响应标头是这样的

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:authorization, content-type, accept, origin
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*

一旦它正常工作,我会将其从 * 更改为仅我的域。但现在我将其保留为 *。

根据要求我的标头。

P粉564192131
P粉564192131

全部回复(2)
P粉952365143

在我的类似案例中,Angular 前端和 Php 后端帮助了下面的代码。首先我发送一个标头:

header("Access-Control-Allow-Origin: http://localhost:4200");   
header("Content-Type: application/json; charset=UTF-8");    
header("Access-Control-Allow-Methods: POST, DELETE, OPTIONS");    
header("Access-Control-Max-Age: 3600");    
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

在他们之后,我可以忽略选项请求:

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {    
   return 0;    
}

这种方法帮助我处理 Angular 中的“post”和“delete”嵌入请求方法。

P粉860370921

好吧,我最近遇到了类似的问题,我只在后端解决了所有问题,没有 .htaccess 的东西。

当浏览器发送跨服务器请求时,它首先发送一个 OPTIONS 请求以确保其有效并且可以发送“真实”请求。 当它从 OPTIONS 获得正确且有效的响应后,才会发送“真正的”请求。

现在,对于后端的两个请求,您需要确保返回正确的标头:content-type、allow-origin、allow-headers 等...

确保在后端的 OPTIONS 请求中,应用程序返回标头并返回响应,而不是继续应用程序的完整流程。

在“真实”请求中,您应该返回正确的标头和常规响应正文。

示例:

//The Response object
    $res = $app->response;

    $res->headers->set('Content-Type', 'application/json');
    $res->headers->set('Access-Control-Allow-Origin', 'http://example.com');
    $res->headers->set('Access-Control-Allow-Credentials', 'true');
    $res->headers->set('Access-Control-Max-Age', '60');
    $res->headers->set('Access-Control-Allow-Headers', 'AccountKey,x-requested-with, Content-Type, origin, authorization, accept, client-security-token, host, date, cookie, cookie2');
    $res->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

    if ( ! $req->isOptions()) {
        // this continues the normal flow of the app, and will return the proper body
        $this->next->call();
    } else {
        //stops the app, and sends the response
        return $res;
    }

要记住的事情:

  • 如果您使用:“Access-Control-Allow-Credentials”= true 确保“Access-Control-Allow-Origin”不是“*”,它必须设置正确的域! (这里流了很多血:/)

  • 定义您将在“Access-Control-Allow-Headers”中获得的允许标头 如果您不定义它们,请求将失败

  • 如果您使用“Authorization: Bearer”,那么“Access-Control-Allow-Headers”也应包含“Authorization”,否则请求将失败
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!