Web API 使用 AJAX 出现问题 / 无法加载资源:服务器以状态码 400 响应 ()。

huangapple go评论75阅读模式
英文:

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(&quot;Login&quot;)]
        public async Task&lt;IActionResult&gt; Login([FromBody] SigninViewModel formData)
        {
            MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t =&gt; t.MemberAccount.Equals(formData.memberAccount));
        
                if (membercredential == null)
                {

                    var test = new { success = false, message = &quot;無此帳號,請重新輸入。&quot; };
                    Console.WriteLine(test);
                    return BadRequest(new { success = false, message = &quot;無此帳號,請重新輸入。&quot; });
                }
                bool isPwdMatch = BCrypt.Net.BCrypt.Verify(formData.memberPassword, membercredential.MemberPassword);
                
                Console.WriteLine(&quot;驗證結果:&quot; + isPwdMatch);

                if (isPwdMatch == false)
                {
                    return BadRequest(new { success = false, message = &quot;帳號或密碼錯誤,請重新輸入。&quot; });
                
                }
            
       
                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 = &quot;登入成功&quot; });
            
            
        }

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(&quot;Login&quot;).addEventListener(&quot;submit&quot;, function (event) {
            event.preventDefault();

            let MemberAccount = document.getElementById(&quot;MemberAccount&quot;).value;
            let MemberPassword = document.getElementById(&quot;MemberPassword&quot;).value;

            const formData=
            {
                memberAccount:MemberAccount,
                memberPassword:MemberPassword
            }

            $.ajax({
                type:&quot;POST&quot;,
                url: &quot;/api/Members/Login&quot;,
                data:JSON.stringify(formData),
                contentType: &quot;application/json&quot;
            }).done(data=&gt;{
                if (data.success) {
                    alert(&quot;Login Success!&quot;);
                    window.location.href = &quot;https://localhost:1111/Home/Index&quot;;
                } else {
                    alert(&quot;Login fail!&quot;);
                }
        }).fail((jqXHR, textStatus, errorThrown) =&gt; {
            console.error(&quot;AJAX error:&quot;, 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);
    }
});

Web API 使用 AJAX 出现问题 / 无法加载资源:服务器以状态码 400 响应 ()。

英文:

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) =&gt; {
            if (jqXHR.status === 400) {               
                const errorResponse = jqXHR.responseJSON; 
                alert(errorResponse.message); 
            } else {
                console.error(&quot;AJAX error:&quot;, textStatus, errorThrown);
            }
        });

Web API 使用 AJAX 出现问题 / 无法加载资源:服务器以状态码 400 响应 ()。

答案2

得分: 0

你尝试在控制器参数中使用[FromBody]了吗?

端点签名应该像这样。

[HttpPost("Login")] public async Task Login([FromBody]SigninViewModel scv)

如果这不起作用,肯定与你从前端发送数据的方式有关。

请告诉我们你是否尝试过这个。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月27日 21:58:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定