是的,Bearer Token身份验证可以与Access-Control-Allow-Credentials:false一起使用。在这种情况下,前端需要在请求头中设置Authorization字段来传递Bearer Token。
后端代码示例:
app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', 'http://example.com'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// 是否允许前端向后端发送凭据(如cookies) res.header('Access-Control-Allow-Credentials', false);
// 如果请求头包含Authorization字段,则验证Token if (req.headers.authorization) { // 验证Token }
next(); }); 其中,Access-Control-Allow-Credentials字段值为false表示不允许前端向后端发送凭据(如cookies)。如果需要允许,请将其值改为true。
前端代码示例:
fetch('http://example.com/api', { credentials: 'include', // 允许发送凭据(如cookies) headers: { Authorization: 'Bearer TOKEN', }, }).then(response => { // 处理响应 }); 其中,fetch函数中的credentials字段需设置为include,表示允许发送凭据(如cookies)。同时,请求头中需要包含Authorization字段,以传递Bearer Token。