在前端使用的 HTTP 库(比如 Axios)配置跨域
import axios from 'axios';
axios.defaults.withCredentials = true;
开发前后端分离 App,在 Webman 设置了跨域,但从前端访问接口时使用session api取不到数据,返回 NULL。
跨域中间件
class Access implements MiddlewareInterface
{
public function process(Request $request, callable $handle): Response
{
if ($request->controller == 'app\controller\XController') {
$response = $handle($request);
$response->withHeaders([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Credentials' => 'true',
'Content-Type' => 'application/json;charset=UTF-8',
'Access-Control-Allow-Methods' => 'GET,POST',
'Access-Control-Allow-Headers' => '*'
]);
return $response;
} else {
return $handle($request);
}
}
}
前端要调用的登出 API
public function logout(Request $request)
{
$session = $request->session();
$uid = $session->get('uid'); // 取回 NULL
Token::where('uid', $uid)->delete();
$session->flush();
return json(['code' => 0, 'msg' => '完成。']);
}
OS: Windows 11 21H2
Webman: 1.5.0
Workerman: 4.1.10
请问怎么解决的?
是中间件没配好,https://www.workerman.net/doc/webman/middleware.html#%E7%A4%BA%E4%BE%8B%EF%BC%9A%E8%B7%A8%E5%9F%9F%E8%AF%B7%E6%B1%82%E4%B8%AD%E9%97%B4%E4%BB%B6 这样写可以
大哥能教教我吗,我也是前后端分离的,session一直获取不到
前端配置好,后端不用动