Issue with Web API and AJAX: Unable to retrieve resource, server returned status code 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 = "登入成功" });
            
            
        }

Input incorrect password and trigger the following code:

return BadRequest(new { success = false, message = "帳號或密碼錯誤,請重新輸入。" }); However, the AJAX call 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, the AJAX call will display alert("Login Success!") and redirect to /Home/Index, however when an action with return BadRequest() is triggered, the AJAX call does not respond. In the browser's console, it shows Failed to load resource: the server responded with a status of 400 (). Please assist in rectifying the above program code, thank you! View image description here

public class SigninViewModel
{
    public string memberAccount { get; set; }
    public string memberPassword { get; set; }
}

Answer №1

When an error occurs and BadRequest() is returned from the backend, a 400 state code will be sent in response. Therefore, it is important to handle this situation in the fail() method as shown in the following code snippet:

.fail((jqXHR, textStatus, errorThrown) => {
            if (jqXHR.status === 400) {               
                const errorResponse = jqXHR.responseJSON; 
                alert(errorResponse.message); 
            } else {
                console.error("AJAX error:", textStatus, errorThrown);
            }
        });

https://i.sstatic.net/i7fJx.gif

Answer №2

Did you attempt to utilize the [FromBody] attribute in the controller parameter?

The endpoint declaration should appear like this.

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

If this method is unsuccessful, it likely pertains to how you are transmitting the data from the front end.

Kindly inform us if you give this a shot.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Read method of the custom JsonConverter<DateTime> in System.Text.Json is not getting utilized when using the Deserialize method

I've encountered an issue with custom datetime formats in System.Text.Json. A custom converter I created was working fine in my API project, but when I tried using the same class in my client, the .Deserialize() methods wouldn't call .Read() on ...

Name or Title of a Polygon/Polyhedron Using Three.js

My page contains a sample code that successfully retrieves the name of an object when a user clicks on it. However, the code works well with cubes and spheres but fails with polygons. To see how the clicks respond, you can check the console logs. What shou ...

What is the origin of function parameters in javascript?

I have implemented the following code: handleOwnerMode = ownerChecked => { this.setState(prev => ({ ownerChecked, showOwner: !prev.showOwner})) // this.setState(prev => ({ ownerChecked: !prev.ownerChecked, showOwner: !prev.showOwner ...

Using regular expressions in JavaScript to work with numbers separated by commas, as well as their comparison operators such as greater than, greater than or

Currently, I have implemented this Regex pattern to validate numbers with decimals (comma separated) /(^\d*\,?\d*[1-9]+\d*$)|(^[1-9]+\d*\,\d*$)/ However, I am now faced with the need to modify it in order to also valida ...

Tips for utilizing a single mongoose default connection across various files in MongoDB?

I'm struggling to figure out how to share a mongoose connection across multiple files. Here's an example: User.js var mongoose = require("../DataAccess/DbConnection"); var userSchema = new Schema({ email: {type: String, required: true,max ...

Decoding json data with targeted API keys

Looking for some assistance here. I've got a JSON data set that looks like this: [ { "positive": 2, "negative": 4 }, { "positive": 9, "negative": 18 }, { "positive": 6, "negative": 12 } ...

Display a pop-up when hovering over a layer with react-leaflet

I am attempting to display a popup when hovering over a layer in react leaflet. Utilizing GeoJson to render all layers on the map and onEachFeature() to trigger the popup on hover, I encountered an issue where the popup only appeared upon click, not hover. ...

Is CakePHP unable to handle multiple Ajax requests simultaneously?

After multiple rounds of editing this post, I keep uncovering new information through testing and debugging. Here is my current situation: I have a method thinker that takes a significant amount of time to process. To address this, I have decided to call ...

The steps to display a partial view within another view in React Native

Attempting to show the View after calling alert("Hi") in the renderMoreView function has been challenging for me. The alert works fine, but displaying the View is where I am encountering issues. class Main extends Component { state = { moreButton: f ...

What is the best way to trigger the Reactjs MUI DatePicker popup to display when clicking inside it for editing the date, without relying on the

As of now, DatePicker displays a calendar icon for opening the date picker popup. While I can eliminate the icon using the disableOpenPicker property, my goal is to open the popup when the user clicks on the Datepicker input field, functioning just like ...

Preserve numerous inputs in local storage

Hope your day is going well. I've been attempting to save multiple inputs by parsing localStorage into JSON using a 'for' loop, but unfortunately, nothing is being saved. The error message in the CONSOLE reads: "Uncaught SyntaxError: Unexpe ...

Your request must be a POST method and only absolute URLs are allowed

I have created a client-side app.js file that makes a post request to a server (code provided below): const fetch = require('node-fetch'); /* Function for POSTing data */ const postData = async ( url = 'http://localhost/8000/add ...

Creating code that is easily testable for a unique test scenario

My function, readFile(path, callback), is asynchronous. The first time it reads a file, it retrieves the content from the file system and saves it in memory. For subsequent reads of the same file, the function simply returns the cached content from memor ...

Retrieving data from a Database using PHP to fetch multiple rows

I've been working on a filter function that uses AJAX and basic PHP to fetch items based on certain criteria. The issue I'm facing is that when there are rows with duplicate IDs, nothing is displayed. I want all rows with the matching ID to be di ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to prev ...

Uploading an image without the submit event is not possible with AJAX

Looking for a way to upload images asynchronously using AJAX? I've scoured the internet for solutions, tried various combinations of codes, but none seem to work without a submit event. I want to stress that I can upload images using a button that tri ...

How can the database for ASP.NET membership be updated with each new page request?

My application scenario involves connecting to different databases based on the subdomains in the URL. Below is the code I have tried: public class Provider : SqlMembershipProvider { public override void Initialize(string name, System.Collec ...

Retrieving the text of a selected option by its value

I need to create a menu that returns text based on a given value. For example, if the value is 0, I want it to return “zero”, and if it's 1, then “one”, and so on. I don't need to know which option is selected or auto-select anything, I j ...

Add an exciting new element to the array within the DOM using knockout.js

Is there a way to make the font color change to red and then back to white when a new item is added to a play by play array using knockout? I know how to achieve this effect on a single property with the provided binding, but I'm unsure of how to do i ...