webman设置了Headers还是会出现跨域问题

黑老怪

问题描述

不设置Header头没有问题,把header头加上就出现

程序代码

<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AccessControl implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        // 如果是opitons请求则返回一个空的响应,否则继续向洋葱芯穿越,并得到一个响应
        $response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
        // 给响应添加跨域相关的http头
        $response->withHeaders([
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', 'Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Authorization, X-Token'),
        ]);
        return $response;
    }
}

报错信息

Access to XMLHttpRequest at 'http://A' from origin 'http://B' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
2220 3 0
3个回答

yongdao35

如果ajax里设置了header,返回的 Access-Control-Allow-Headers 要把这个header加进去,否则报跨域错误

  • 黑老怪 2023-02-10

    已经设置了X-Token,但是还是没用.

  • yongdao35 2023-02-10
    'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', 'Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Authorization, X-Token'),

    改成

    'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Authorization, X-Token',
  • 黑老怪 2023-02-10

    还是不行.

ersic

跨域设置重复了,nginx 设置了webman就别设置了。

  • 黑老怪 2023-02-10

    不是nginx,直接用的端口访问也是这样.

  • Jgcoder 2023-03-02

    我也遇到怎么问题?你解决了没?

  • 黑老怪 2023-03-02

    在路由页面增加一句 我是这样解决的
    Route::options('[{path:.+}]', function (){ return response(''); });

  • Jgcoder 2023-03-03

    我的加了这句也不行,必须要用 Route::any

owenzhang

我是直接nginx 设置

  • 暂无评论
年代过于久远,无法发表回答
×
🔝