英文:
Web API With AJAX problem /Failed to load resource: the server responded with a status of 400 ()
问题
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] SigninViewModel formData)
{
MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t => t.MemberAccount.Equals(formData.memberAccount));
if (membercredential == null)
{
var test = new { success = false, message = "無此帳號,請重新輸入。" };
Console.WriteLine(test);
return BadRequest(new { success = false, message = "無此帳號,請重新輸入。" });
}
bool isPwdMatch = BCrypt.Net.BCrypt.Verify(formData.memberPassword, membercredential.MemberPassword);
Console.WriteLine("驗證結果:" + isPwdMatch);
if (isPwdMatch == false)
{
return BadRequest(new { success = false, message = "帳號或密碼錯誤,請重新輸入。" });
}
var LoginData = new
{
MemberId = member.MemberId,
MemberName = member.MemberName,
MemberPoint = member.MemberPoint
};
string json = JsonSerializer.Serialize(LoginData);
Console.WriteLine(json);
HttpContext.Session.SetString(CDictionary.SK_LOINGED_USER, json);
return Ok(new { success = true, message = "登入成功" });
}
document.getElementById("Login").addEventListener("submit", function (event) {
event.preventDefault();
let MemberAccount = document.getElementById("MemberAccount").value;
let MemberPassword = document.getElementById("MemberPassword").value;
const formData =
{
memberAccount: MemberAccount,
memberPassword: MemberPassword
}
$.ajax({
type: "POST",
url: "/api/Members/Login",
data: JSON.stringify(formData),
contentType: "application/json"
}).done(data => {
if (data.success) {
alert("登入成功!");
window.location.href = "https://localhost:1111/Home/Index";
} else {
alert("登入失敗!");
}
}).fail((jqXHR, textStatus, errorThrown) => {
console.error("AJAX error:", textStatus, errorThrown);
});
});
public class SigninViewModel
{
public string memberAccount { get; set; }
public string memberPassword { get; set; }
}
英文:
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] SigninViewModel formData)
{
MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t => t.MemberAccount.Equals(formData.memberAccount));
if (membercredential == null)
{
var test = new { success = false, message = "無此帳號,請重新輸入。" };
Console.WriteLine(test);
return BadRequest(new { success = false, message = "無此帳號,請重新輸入。" });
}
bool isPwdMatch = BCrypt.Net.BCrypt.Verify(formData.memberPassword, membercredential.MemberPassword);
Console.WriteLine("驗證結果:" + isPwdMatch);
if (isPwdMatch == false)
{
return BadRequest(new { success = false, message = "帳號或密碼錯誤,請重新輸入。" });
}
var LoginData = new
{
MemberId = member.MemberId,
MemberName = member.MemberName,
MemberPoint = member.MemberPoint
};
string json = JsonSerializer.Serialize(LoginData);
Console.WriteLine(json);
HttpContext.Session.SetString(CDictionary.SK_LOINGED_USER, json);
return Ok(new { success = true, message = "登入成功" });
}
Enter the wrong password, and execute
return BadRequest(new { success = false, message = "帳號或密碼錯誤,請重新輸入。" });
this code, but ajax does not execute the action。
Failed to load resource: the server responded with a status of 400 ()
document.getElementById("Login").addEventListener("submit", function (event) {
event.preventDefault();
let MemberAccount = document.getElementById("MemberAccount").value;
let MemberPassword = document.getElementById("MemberPassword").value;
const formData=
{
memberAccount:MemberAccount,
memberPassword:MemberPassword
}
$.ajax({
type:"POST",
url: "/api/Members/Login",
data:JSON.stringify(formData),
contentType: "application/json"
}).done(data=>{
if (data.success) {
alert("Login Success!");
window.location.href = "https://localhost:1111/Home/Index";
} else {
alert("Login fail!");
}
}).fail((jqXHR, textStatus, errorThrown) => {
console.error("AJAX error:", textStatus, errorThrown);
});;
});
If the login is successful, ajax will alert("Login Success!"),and
switch page to /Home/Index,but
the action about return BadRequest() is executed, but ajax does not make any action. In the developer's introduction, it appears that Failed to load resource: the server responded with a status of 400 (), please help me to modify the above program code, thank you!
enter image description here
public class SigninViewModel
{
public string memberAccount { get; set; }
public string memberPassword { get; set; }
}
答案1
得分: 0
当在后端返回BadRequest()
时,响应中将返回400状态码,因此您需要在fail()
方法中处理它。参考以下代码:
.fail((jqXHR, textStatus, errorThrown) => {
if (jqXHR.status === 400) {
const errorResponse = jqXHR.responseJSON;
alert(errorResponse.message);
} else {
console.error("AJAX error:", textStatus, errorThrown);
}
});
英文:
When you return BadRequest()
in backend, It will return 400 state code in response, So you need to handle it in fail()
method. refer to this code:
.fail((jqXHR, textStatus, errorThrown) => {
if (jqXHR.status === 400) {
const errorResponse = jqXHR.responseJSON;
alert(errorResponse.message);
} else {
console.error("AJAX error:", textStatus, errorThrown);
}
});
答案2
得分: 0
你尝试在控制器参数中使用[FromBody]了吗?
端点签名应该像这样。
[HttpPost("Login")] public async Task
如果这不起作用,肯定与你从前端发送数据的方式有关。
请告诉我们你是否尝试过这个。
英文:
Have you tried to use [FromBody] in the controller parameter.
The endpoint signature should be like this.
[HttpPost("Login")] public async Task<IActionResult> Login([FromBody]SigninViewModel scv)
If this not work defintely has to be related to the way you are sending the data from the frontend.
Please make us know if you try this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论