我在使用 jQuery 访问 AJAX 请求响应中名为 X-Subject-Token 的自定义标头时遇到问题。这是我的代码:
async function submitHandler(e) {
e.preventDefault();
let BASE_URL = "http://{my-ip}:3005"
if (usernameInput.value && passwordInput.value) {
let json = {
name: usernameInput.value,
password: passwordInput.value
}
console.log(json)
try {
let response = await fetch(${BASE_URL}/v1/auth/tokens, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(json)
});
if (response.ok) {
let token = String(response.headers.get("X-Subject-Token"))
console.log(token)
response.headers.forEach(h=>{
console.log(h)
})
}
let data = await response.json();
console.log(data);
} catch (err) {
console.log(err)
}
}
}
我已使用浏览器开发人员工具验证 X-Subject-Token 标头是否存在于响应中。但是,当我尝试使用 jqXHR.getResponseHeader('X-Subject-Token') 访问它时,它仅返回内容类型 ,内容长度和缓存控制。
我还检查了 CORS 问题,但服务器似乎已正确配置以允许自定义标头。
keyrock:
image: quay.io/fiware/idm:${KEYROCK_VERSION}
container_name: fiware-keyrock
hostname: keyrock
networks:
default:
ipv4_address: 172.18.1.5
depends_on:
- mysql-db
- authzforce
ports:
- "${KEYROCK_PORT}:${KEYROCK_PORT}" # localhost:3005
environment:
- DEBUG=idm:*
- IDM_DB_HOST=mysql-db
- IDM_DB_PASS_FILE=/run/secrets/my_secret_data
- IDM_DB_USER=root
- IDM_HOST=http://localhost:${KEYROCK_PORT}
- IDM_PORT=${KEYROCK_PORT}
- IDM_HTTPS_PORT=${KEYROCK_HTTPS_PORT}
- IDM_ADMIN_USER=alice
- [email protected]
- IDM_ADMIN_PASS=test
- IDM_PDP_LEVEL=advanced
- IDM_AUTHZFORCE_ENABLED=true
- IDM_AUTHZFORCE_HOST=authzforce
- IDM_AUTHZFORCE_PORT=${AUTHZFORCE_PORT}
- IDM_CSP_FORM_ACTION=*
- IDM_CORS_ENABLED=true
- IDM_CORS_ORIGIN=*
- IDM_CORS_METHODS=GET,HEAD,PUT,PATCH,POST,DELETE
- IDM_CORS_ALLOWED_HEADERS=content-type,X-Auth-Token,Tenant-ID,Authorization,Fiware-Service,Fiware-ServicePath,NGSILD-Tenant,NGSILD-Path,X-Subject-Token
- IDM_CORS_CREDENTIALS=true
- IDM_CORS_PREFLIGHT=true
- IDM_CORS_EXPOSED_HEADERS=content-type,X-Auth-Token,Tenant-ID,Authorization,Fiware-Service,Fiware-ServicePath,NGSILD-Tenant,NGSILD-Path,X-Subject-Token
任何人都可以帮助我理解为什么我无法使用 jQuery 访问 AJAX 响应中的 X-Subject-Token 标头吗?任何见解或建议将不胜感激。
将选项 'Access-Control-Expose-Headers' : 'X-Subject-Token' 添加到请求标头:
let response = await fetch(${BASE_URL}/v1/auth/tokens, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Expose-Headers": "X-Subject-Token"
},
body: JSON.stringify(json)
});