webman-admin 打包之后出現(xiàn)跨域問題,服務(wù)端用的nginx代理,按照手冊上設(shè)置的,Nginx也配置了跨域,前端請求的時候,還會提示跨域錯誤
nginx配置
upstream webman {
server 172.31.34.153:8787;
keepalive 10240;
}
server {
listen 8989;
listen [::]:8989;
server_name IP:8989;
access_log off;
index index.html index.htm index.php;
root /data/wwwroot/IP:8787;
include /usr/local/nginx/conf/rewrite/none.conf;
#error_page 404 /404.html;
#error_page 502 /502.html;
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' '*';
add_header 'Access-Control-Max-Age' 86400;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_set_header Connection "";
if (!-f $request_filename){
proxy_pass http://webman;
}
}
}
webman跨域中間件
<?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請求則返回一個空的響應(yīng),否則繼續(xù)向洋蔥芯穿越,并得到一個響應(yīng)
$response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
// 給響應(yīng)添加跨域相關(guān)的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', '*'),
]);
return $response;
}
}
Access to XMLHttpRequest at 'http://ip:8989/api/sport/1?pageSize=20&page=1&type=1' from origin 'http://ip' 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.
webman-admin 最新版
1、nginx 改完配置要重啟才能生效。
2、webman-admin是應(yīng)用插件,手冊說每個應(yīng)用插件有自己獨立的配置和主項目是獨立的,所以給webman-admin插件設(shè)置跨域應(yīng)該設(shè)置plugin/admin/config/middleware.php
而不是主項目中的config/middleware.php
。
3、既然都發(fā)布到外網(wǎng)了,前端和后端域名端口應(yīng)該保持一致,保持一致自然就不會跨域了,自然沒這些麻煩。
大佬,非常的神奇,webman-admin 設(shè)置了官網(wǎng)的跨域中間件,然后nginx又設(shè)置了跨域,這樣會導(dǎo)致報錯,為什么呢?
webman-admin 設(shè)置了官網(wǎng)的跨域中間件,然后nginx又設(shè)置了跨域,這樣會導(dǎo)致跨域不成功,有沒有大佬明白是為什么???把webman-admin的跨域中間件取消,就正常了。。。
具體原因瀏覽器會提示,類似 the xxx header contains multiple values xxx, but only one is allowed
。翻譯過來就是某個跨域header只允許設(shè)置一個值,不允許重復(fù)設(shè)置。
當(dāng)然,你最開始的報錯No 'Access-Control-Allow-Origin' header is present on the requested resource
不是重復(fù)設(shè)置跨域頭,是沒設(shè)置跨域頭。兩個是不同的問題。
真的太對了大佬,為什么不能重復(fù)設(shè)置呢?nginx算是前端的跨域,webman跨域中間件算是后端的跨域,前后端都設(shè)置允許跨域這個有問題嗎?
webman返回的數(shù)據(jù)會經(jīng)過nginx轉(zhuǎn)發(fā)給客戶端,webman加了跨域header,nginx又加了一次,所以跨域header重復(fù)了