Executing the get function using javascript

Recently, I've been experimenting with using Web Api Asp.Net alongside Javascript to execute my controller. Here's an example of how I've been approaching this:

JS

 function loadCatalog() {
            apiService.get("../../api/CatalogoRegistro/get/", null,
                function (res) {
                    $scope.Catalogos = res.data.Nombre; 
                },
                errorCatalog);
        }

Controller

[AllowAnonymous]
    [HttpGet]
    [Route("{catalog}")]
    public HttpResponseMessage Fetch(HttpRequestMessage req, string catalog)
    {
        return CreateHttpResponse(req, () =>
        {
            HttpResponseMessage response = null;                
            var cr = _pService.List(param => param.Catalogos.Name.Equals(catalog));
            IEnumerable<CatalogoRegistroViewModel> crs = Mapper.Map<IEnumerable<CatalogoRegistro>, IEnumerable<CatalogoRegistroViewModel>>(cr);
            var version = req.Headers.GetValues("Version").FirstOrDefault();
            List<string> errors = new List<string>();

            if(cr==null)
            {
                errors.Add("The catalog does not exist");
            }
            if(errors.Count>0)
                response = req.CreateResponse(HttpStatusCode.BadRequest, new { success = false, errors });
            else 
            {
                response = req.CreateResponse<IEnumerable<CatalogoRegistroViewModel>>(HttpStatusCode.OK, crs);   
            }

            return response;
        });
    }

Angular View

<div class="page-head">
    <div class="page-title">
        <h1>
            Generic Catalogs
            <small>Manage Generic Catalogs of Applications</small>
        </h1>
    </div>
</div>
<div class="row">
<div class="col-md-12">
    <div class="portlet box blue">
        ... // (Content shortened for brevity)
    </div>
</div>
</div>

However, I encountered an issue that states

GET http://localhost:55720/api/CatalogoRegistro/get/ 404 (Not Found)

I'm currently puzzled on why the routing for my api is causing this problem. Any insights would be greatly appreciated.

Answer №1

When you're attempting to use [RoutePrefix("api/Catalogo")] along with api/CatalogoRegistro/get, it seems like there may be confusion about what parameter should be passed in. To clarify, the correct format should be /api/Catalogo/{catalogo}, where {catalogo} represents the value you need for your GET request.

Answer №2

[RoutePrefix("api/Catalogo")] essentially specifies that the URL should be api/Catalogo rather than api/CatalogoRegistro.

function loadCatalog() {
   apiService.get("../../api/Catalogo", null,
   function (res) {
      $scope.Catalogs = res.data.Name; 
   },
   errorCatalog);
}

If you want to send catalog from Angular to the Web API, you will likely need to use the second argument -

function loadCatalog() {
   apiService.get("../../api/Catalogo", catalog,
   function (res) {
      $scope.Catalogs = res.data.Name; 
   },
   errorCatalog);
}

Answer №3

Give this a shot:

When working with your WebApi

[Route("api/CatalogoRegistro/retrieve/{catalog}")]

Using JavaScript

 function loadCatalog() {
        var catalogValue = "inputYourValueHere";
        apiService.get("/api/CatalogoRegistro/retrieve/" + catalogValue, null,
            function (res) {
                $scope.Catalogs = res.data.Name; 
            },
            errorCatalog);
    }

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

moodle - eliminate the need for grading at the same time

I'm currently setting up a Moodle installation and I'm looking for suggestions on how to prevent simultaneous grading. My goal is to have several evaluators grading students across various courses without any conflicts. If you have any recommend ...

We encountered a problem while trying to create the route "/": Minification of HTML failed in Nuxt js

After successfully developing a Nuxt app that runs perfectly with "npm run dev," I encountered an error when generating the site using "npx nuxt generate." Despite my efforts, I cannot locate the source of the error. Any assistance would be greatly appre ...

Is there a way to change the format of a date and time from YYYY-MM-DD hh mm ss to MonthName, date, year | Hour:Minutes (am/pm) using

How can I convert the date string (2013-03-10 19:43:55) into the format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery? ...

Determine whether a div that has been generated automatically has been selected by the user

My JSON file contains a list of elements, each creating a container. See the code below: $.getJSON('/data/risks.json', function(data) { var html = ''; $.each(data.risk, function(key, value){ html += '<div class="elementlis ...

Is it possible for me to utilize the webAudio API in Chrome to connect to the local audio output stream?

Currently, I am working on audio analysis for a visualizer application running on my computer. I am wondering if there is a way to directly access the output audio data stream from the browser? For this project, I am using JavaScript along with the three ...

Assorted Three.js particles

As a beginner in the world of three.js, I'm currently tackling the challenge of incorporating 1000 particles, each unique in size and color. The current roadblock I'm facing is that all particles end up the same color and size when using a Partic ...

Obtaining ASP.NET 4.5 (installation or update) within my Visual Studio 2013 setup

I've been researching the latest features of ASP.NET 4.5, but I'm unsure of how to access them. My searches on Google haven't yielded any helpful results. According to this source, it seems I'm still using ASP.NET 4.0.30319.34014 (Sys ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

Arranging files based on the total amount of a particular category within an array of related documents

Here is the structure of my main schema: _id: id, random: random, cards: [objectId, objectId, ...] //ref to cards An example of a card in the schema: _id: id, random: random, random: random, clicks: 15. I am looking to sort the top schema base ...

Checking the status of a checkbox after submitting using AngularJs

For my first application, I am utilizing AngularJs and JavaScript to display information from an API as checkboxes. Currently, the functionality is working well, but I am unsure how to validate if any checkbox options are checked with a submit button. Aft ...

Updating the configuration settings for CKEditor 5 using Reactjs

I followed the configuration provided in another answer at But, I am facing an issue: Failed to compile. ./src/components/cards/CreateCard.js Line 59:22: Parsing error: Unexpected token, expected "}" 57 | editor={ClassicEditor} 58 | ...

Exploring the Power of Vue 3 in Manipulating the DOM

Hello everyone, I am a beginner with Vue and I am interested in learning how to modify the DOM without relying on methods such as document.querySelector or getElementById. Let's take for instance this input: <input id="myInputId" class=& ...

Resetting the quiz by utilizing the reset button

Hello everyone, I'm new to this platform called Stack Overflow. I need some help with my quiz reset button. It doesn't seem to be working as intended. According to my code, when the reset button is clicked at the end of the quiz, it should bring ...

What causes the exception in JavaScript to be an empty object?

try { let temporary = null; temporary.split(','); } catch (error) { Logger().info('caught error: ', error, error.constructor); } output: caught error: {} undefined I attempted to use JSON.stringify and encountered the sa ...

Loop within a promise results in undefined

Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it. getCodesOfOneMerchant(merchantDataEntry: MerchantData ...

Input information into the system from the successful response found on a different page

After receiving my ajax response successfully, I want to redirect to a new aspx page where there are 30 input type text controls. My goal is to populate all the values in those controls. How can I achieve this? Any suggestions? This is what I have attempt ...

Instructions on establishing a connection with a MongoDB server using JavaScript

Hello all, I am a complete beginner when it comes to working with mongodb and java script. I am currently trying to figure out how to establish a connection to my local mongodb instance using java script so I can retrieve a list of documents. Does anyone ...

Issues arise when trying to use a JavaScript function within an HTML form, with an error message stating "TypeError: total

Recently, I encountered an issue with a straightforward JavaScript function that calculates user input. The function performed as expected when I tested it without the form tag. However, when I tried using the same code within the form tag, an error was di ...

I'm struggling to understand how to insert the JSON response into an HTML element

I am encountering an issue with my code where the response from the API call is not displaying on the HTML page. I'm unsure why it's not showing up even though the page loads successfully. <!DOCTYPE html> <html> <head> <title ...

Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS fun ...