无法使用 JavaScript 在客户端获取自定义 header
Cannot Get custom header at client side using JavaScript
我正在尝试发送在服务器端设置名为“x-custom-token”的自定义 header 的响应,并且浏览器正在接收它。但是在客户端。我无法获取它。
这是我的服务器端代码(.Net 框架)。
[AllowAnonymous]
[HttpPost]
//[EnableCors(origins: "*", headers: "*", methods:"*",exposedHeaders: "x-custom-token")]
[AllowCrossSiteAttribute]
//[ValidateAntiForgeryToken]
public ActionResult Login(string account, string password)
{
if (account == null || password == null)
{
throw new ArgumentNullException("account or password is null");
}
try
{
if (this.userService.CheckUserData(account, password))
{
string roleName = this.userService.GetRole(account, password);
string token = this.jWTService.GenerateToken(account, roleName);
Response.AppendHeader("Access-Control-Expose-Headers", "x-custom-token");
Response.AppendHeader("x-custom-token", token);
Response.Redirect("~/Home/Index");
return Json("Ok");
}
else
{
Response.StatusCode = 204;
Response.Redirect("~/Login/login");
return Json("no permission");
}
}
catch (Exception ex)
{
Response.StatusCode = 400;
Response.StatusDescription = ex.Message;
Response.Redirect("~/Login/login");
return Json("no permission");
}
}
这是客户端 (Javascript):
const loginButton = document.getElementsByClassName("login")[0];
loginButton.addEventListener("click", async function () {
const account = document.getElementsByClassName("accountInput")[0].value;
const password = document.getElementsByClassName("passwordInput")[0].value;
const body = `account=${account}&password=${password}`;
const re = await sendRequest("/Login/login", "POST", { "Content-Type": "application/x-www-form-urlencoded" }, body);
if (re.status === 200) {
console.log(re);
console.log(re.headers.get("access-control-expose-headers"));
console.log(re.headers.get("x-custom-token"));
console.log(re.headers.get("x-aspnet-version"));
debugger
window.location.href = `${window.location.protocol}//${window.location.hostname}:${Number(44398)}/Home/Index`;
}
else {
alert(`response status: ${re.status} ${re.json()}`);
}
}, false);
在这行代码中 console.log(re.headers.get("x-custom-token"));
我总是得到 null....
还添加了 Access-Control-Expose-Headers
。
我确定浏览器对此自定义有响应 header
browser response
这是我的sendRequest()
方法:
async function sendRequest(path, method, headers, body) {
const protocol = window.location.protocol;
const domainName = window.location.hostname;
const port = "44398"
let options = {
method: method,
headers: headers,
}
if (body) {
options.body = body;
}
const response = await fetch(`${protocol}//${domainName}:${port}${path}`, options)
return response;
}
我想弄清楚发生了什么。
在 returning return 之前 Json("Ok");你正在呼叫 Response.Redirect("~/Home/Index");
它重定向到新的获取请求,而不是 return 对当前客户端调用的响应。
而不是调用 Response.Redirect("~/Home/Index");在 return return Json("确定") 之前; ,
您可以从服务器端删除它并在 javascript 函数中的 client-side 处处理 ajax 请求的响应。
请参阅下文url以供您理解。
.
我正在尝试发送在服务器端设置名为“x-custom-token”的自定义 header 的响应,并且浏览器正在接收它。但是在客户端。我无法获取它。
这是我的服务器端代码(.Net 框架)。
[AllowAnonymous]
[HttpPost]
//[EnableCors(origins: "*", headers: "*", methods:"*",exposedHeaders: "x-custom-token")]
[AllowCrossSiteAttribute]
//[ValidateAntiForgeryToken]
public ActionResult Login(string account, string password)
{
if (account == null || password == null)
{
throw new ArgumentNullException("account or password is null");
}
try
{
if (this.userService.CheckUserData(account, password))
{
string roleName = this.userService.GetRole(account, password);
string token = this.jWTService.GenerateToken(account, roleName);
Response.AppendHeader("Access-Control-Expose-Headers", "x-custom-token");
Response.AppendHeader("x-custom-token", token);
Response.Redirect("~/Home/Index");
return Json("Ok");
}
else
{
Response.StatusCode = 204;
Response.Redirect("~/Login/login");
return Json("no permission");
}
}
catch (Exception ex)
{
Response.StatusCode = 400;
Response.StatusDescription = ex.Message;
Response.Redirect("~/Login/login");
return Json("no permission");
}
}
这是客户端 (Javascript):
const loginButton = document.getElementsByClassName("login")[0];
loginButton.addEventListener("click", async function () {
const account = document.getElementsByClassName("accountInput")[0].value;
const password = document.getElementsByClassName("passwordInput")[0].value;
const body = `account=${account}&password=${password}`;
const re = await sendRequest("/Login/login", "POST", { "Content-Type": "application/x-www-form-urlencoded" }, body);
if (re.status === 200) {
console.log(re);
console.log(re.headers.get("access-control-expose-headers"));
console.log(re.headers.get("x-custom-token"));
console.log(re.headers.get("x-aspnet-version"));
debugger
window.location.href = `${window.location.protocol}//${window.location.hostname}:${Number(44398)}/Home/Index`;
}
else {
alert(`response status: ${re.status} ${re.json()}`);
}
}, false);
在这行代码中 console.log(re.headers.get("x-custom-token"));
我总是得到 null....
还添加了 Access-Control-Expose-Headers
。
我确定浏览器对此自定义有响应 header
browser response
这是我的sendRequest()
方法:
async function sendRequest(path, method, headers, body) {
const protocol = window.location.protocol;
const domainName = window.location.hostname;
const port = "44398"
let options = {
method: method,
headers: headers,
}
if (body) {
options.body = body;
}
const response = await fetch(`${protocol}//${domainName}:${port}${path}`, options)
return response;
}
我想弄清楚发生了什么。
在 returning return 之前 Json("Ok");你正在呼叫 Response.Redirect("~/Home/Index"); 它重定向到新的获取请求,而不是 return 对当前客户端调用的响应。
而不是调用 Response.Redirect("~/Home/Index");在 return return Json("确定") 之前; , 您可以从服务器端删除它并在 javascript 函数中的 client-side 处处理 ajax 请求的响应。
请参阅下文url以供您理解。
.