Encountering a 404 error in Spring v2.3.2 while trying to send a post request using AJAX axios on a Tom

My spring application is working fine on my local machine and deploys successfully on both Tomcat 8 and 9. However, when trying to post data with AJAX using Axios, I keep receiving a 404 error message. I have double-checked the URL on both the front-end and back-end, and everything seems to be correct.

CONTROLLER

@Controller
public class StudentController {

@Autowired
StudentSearchRepo studentSearchRepo;

@ResponseBody
@RequestMapping(value="/csis/ajax/student/search", method = RequestMethod.POST)
public StudentSearch searchStudent(@RequestBody Student student)
{

    StudentSearch studentSearch = studentSearchRepo.findByStudentNumber(student.getStudentNumber());

    if(studentSearch == null)
    {
        StudentSearch studentSearch1 = new StudentSearch();
        studentSearch1.setApplicantNumber(1);
        return studentSearch1;
    }
    return studentSearch;

}
}

JAVASCRIPT

<script th:inline="javascript">

    new Vue({
        el: "#student_details",

        data:{
            studentNumber: '',
            search_content: false,
            result_set: false,
            student: []
        },



        methods:{

            searchStudent: function () {

                this.search_content = false;

                axios.post("/csis/ajax/student/search",{
                    studentNumber: this.studentNumber
                }).then(response =>{

                  

                     if(response.data.applicantNumber === 1)
                     {
                       
                         this.search_content = false;
                         this.result_set = true;

                     }else {
                         this.search_content = true;
                         this.result_set = false;
                         this.student = response.data
                      

                     }
                  
                }).catch( error =>{
                    console.log(error)
                })
            }

        }


    })
</script>

Any assistance would be greatly appreciated as I believe there might be something I am overlooking.

Answer №1

It appears that your application is optimized for an Embedded Web Server rather than an external Tomcat server. This discrepancy may be due to the different paths used for accessing the searchStudent method.

To address this issue, make sure to include the following line in your properties file:

server.servlet.context-path=/csis

Additionally, update the value of the @RequestMapping as shown below:

    @ResponseBody
    @RequestMapping(value="/ajax/student/search", method = RequestMethod.POST)
    public StudentSearch searchStudent(@RequestBody Student student)
    {

        StudentSearch studentSearch = studentSearchRepo.findByStudentNumber(student.getStudentNumber());

        if(studentSearch == null)
        {
            StudentSearch studentSearch1 = new StudentSearch();
            studentSearch1.setApplicantNumber(1);
            return studentSearch1;
        }
        return studentSearch;

    }

One important point to remember is:

Spring Boot Applications typically serve content on the root context path (“/”)

In certain situations where a custom path is necessary, like in your case, it's advisable to define your own path.

Furthermore, ensure that the Tomcat server dependency is properly set and excluded from some Spring Boot libraries:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <!-- By @ASopia: Exclude the Tomcat dependency-->
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

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

After an AJAX request, the URL is automatically updated with $_GET parameters

I have the following code snippet: $('#loginnow').click(function() { var login_useroremail = $('input[name="login_useroremail"]').val(); var login_password = $('input[name="login_password"]').val(); $.ajax ...

What is the best way to extract information from a JSON object?

I am currently utilizing the JSON.js library provided by JSON.org. <% JSONReturn = GetDistance(Sample) // this function returns a string in JSON format (specifically from the ArcGIS server Solve Route function) JSONObject = JSON.parse(JSONReturn,"Tota ...

Assigning values to a 3D array

Is it possible to streamline the process of assigning values in a 3D array in Java? If so, how can this be done? int [][][]array = new int[3][][]; array[0] = new int [4][5]; array[1] = new int [5][5]; array[2] = new int [3][5]; ar ...

What could be causing the CORS policy to block GET requests?

In my recent project, I have been developing a hybrid app that utilizes express and cors. This application is responsible for sending both get and post requests from a client JavaScript file to a server file. Everything was functioning smoothly until I sta ...

Update dataTable with new data fetched through an ajax call from a separate function defined in a different

I need to refresh the data in my datatable after using a function to delete an item. The function for deleting is stored in a separate file from the datatable. Here is the delete function code: function removeFunction(table,id) { var txt= $('.ti ...

The utilization of ReentrantLock within Java Flight Recorder

How does a ReentrantLock mechanism work? I'm interested in locating it within a Java Flight Recording. I initially thought it would be found under the Java Monitor Wait section, but it seems that is not the case. Context: I am troubleshooting an is ...

Step-by-step guide on adding an onclick event to an element with a customized input for the function

So I have multiple HTML elements, but for simplicity's sake, let's focus on just one with the id <div class="block" id="block0"></div>. I want to add an onclick event using JavaScript like this: <div class=&qu ...

Error: karma cannot locate the templateUrl for Angular component

I'm encountering some issues while running tests on angular directives with karma. The problem arises when the directive comes from a templateUrl and is not being translated properly. Here's my karma.conf.js configuration: 'use strict&apos ...

Communication with parent components via event emissions in Vue is not possible

I'm working on a form with the following structure: <template> <form @submit.prevent=""> <input v-model="objective"> <div> <button @click="addTask">add</button> </div> </form& ...

What takes precedence in npm scripts - local dependencies or global ones?

When using npm scripts, the ./node_modules/.bin path is automatically added to your PATH. This means that by simply running npm test with the provided package.json, npm will utilize the local version of mocha located in ./node_modules/.bin. "scripts": { ...

Props retrieved directly from the Vue 3 setup do not have reactivity

I'm currently working on a Vue.js application and I'm facing an issue when trying to pass props to a child component. The error message I'm getting is: Getting a value from the props in root scope of setup() will cause the value to lose re ...

POST method error 400 encountered

Whenever I execute my ajax jquery function, I encounter a 400 error Here is my code. All Postman tests pass successfully, but when the web app runs, it fails. I'm not sure if it's a coding issue or something related to HTML5. Can anyone offer as ...

Despite successfully loading the GLTF model and textures using Threejs, the model does not appear on the screen

After mastering the ins and outs of three.js, I've encountered a roadblock. Despite successfully uploading my model to the server, it refuses to appear in the three.js window. Adding a light source alongside the model didn't yield any results eit ...

Angularjs app unable to retrieve data after deployment

Currently, I am working on a local server developing an AngularJS app on localhost. I have shared the project link with my colleagues using my current IP address within the network to receive feedback. However, when they visit the page, no data is displaye ...

The Angular 8 click event operates like a JavaScript onload function

I have integrated my angular application into an iframe portlet. On the parent JSP page, there is a form with an invisible submit button. Clicking this button opens a popup window from an external application. I am attempting to trigger the click event o ...

Failure to display div upon onmouseover event

The div 'hidden-table' is causing issues as it does not display even though the style attribute 'display:none' has been removed. I have attempted to show the table separately outside of the echo statement, and it appears to work correct ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Extract the SQL queries generated by Hibernate in OpenUnderWriter

I recently installed the openunderwriter insurance solution with its source code and configured it to run from Eclipse. The project uses Liferay framework and Hibernate for data persistence in MySQL database. I am looking to debug SQL queries that are sent ...

It appears that the fetch operation does not wait as expected

Having some trouble with a caching system in my code where I'm trying to load the same template quickly. Even though I've tried implementing a basic caching mechanism to only fetch the template if it hasn't been loaded before, I'm strug ...

What methods can be used to identify modifications in a URL using a chrome extension?

Currently, I am diving into the world of creating chrome extensions. I encountered an issue where my context scripts fail to run unless onload is triggered. Even something as simple as alert("test"); doesn't work. This problem persists when ...