Can you provide me with the accurate URL to access my Web API endpoint in asp.net?

I'm currently utilizing an API in my asp.net project and attempting to access it from my JavaScript file. However, I suspect there may be an issue with the URL I am using. Here is the controller and method I am trying to retrieve:

[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    [HttpGet("get-user-by-id")]
    public async Task<IActionResult> GetUser(string email, string 
                                                          password)
{
    var result = await _userService.GetUser(email, password);

    if (result == null) return NotFound();

    return Ok(result);
}
}
    

Below is the fetch function within my JavaScript file:

fetch('https://"mylocalhost"/api/User/get-user-by-id', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email, password }),
    })
      .then(function (response) {
        if (!response.ok) {
          throw new Error('HTTP error! Status: ' + response.status);
        }
        return response.json();
      })
      .then(function (data) {
        console.log('Login success:', data);
        window.location.href = 'profile.html';
      })
      .catch(function (error) {
        console.error('Login error:', error.message);
        if (error.message.includes('401')) {
          console.log('Incorrect username or password');
        } else {
          console.log('An error occurred during login');
        }
      });

Please note that "my-local-host" is different from what I have mentioned here.

Answer №1

To optimize the functionality, consider switching from method: 'POST' to method: 'GET' in your JavaScript function

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

Is it feasible to showcase certain debug messages within the HTML code directly from a .cs file?

Here's the issue I'm facing: I have both my view and controller set up. The controller accesses backend classes and methods. Now, I want to create a debug version of my site. In this debug version, I want to display information generated in the ...

Merge text inputs to preview content prior to form submission

I've been on the hunt for a solution to display the collective values entered into multiple text box fields as they are being typed. Currently, I have 6 text boxes (description1, description2, description3, description4, description5, description6) wh ...

Enhanced compatibility with Touch.radiusX feature on smartphone and tablet devices

Curious if anyone knows about the level of support for this property. I am currently using the PR0C0D1N6 app on an iPhone 4 and based on the specifications, when radiusX is not supported it should default to 1. However, in my case, radiusX is showing as un ...

Animating object on display and returning it with keyframes

Given the code snippet below: <div class="leftBox"> <div class="mainNode" ></div> </div> <script type="text/javascript"> $('.mainNode').click(function() { var element = $('.mainNode'); if (!ele ...

Generating and removing key-value pairs in JavaScript associative arrays on the fly

Currently utilizing jQuery version 1.6 My JavaScript skills are not the strongest and I am in need of dynamically creating an array with 2 dynamic parameters: json.id and json.name. The desired structure of the array should be: [ [json.id] [ ...

What solutions are available for resolving the devServer issue in webpack?

Any help or advice would be greatly appreciated. I have configured webpack and everything works in production mode, but the webpack-dev-server is not recognizing static files and is giving the error "Cannot get /". How can I resolve this issue? Thank you i ...

Mongoose faces difficulty in locating records that were not initially generated using mongoose

After successfully creating a collection and a document in a local running database using mongosh, I encountered an issue while trying to access it via mongoose. Despite querying all documents using a model that matches the collection I created, the docume ...

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Encountered an error while attempting to send a POST request to InfluxDB from an ASP

I encountered an issue while attempting to send a POST request to my local influxDB. The response I received was StatusCode: 400, ReasonPhrase: 'Bad Request' HttpClient client = new HttpClient(); HttpRequestMessage requestMessage = new HttpReq ...

Tips for reusing multiple sequences of chained transitions in D3

Looking for a more efficient way to code two lengthy sequences of chained transitions with varying order, properties, and attributes. For example, one sequence might be a, b, c, d, e, f, g, h, and the other e, f, g, h, a, b, c, d. Tried the code below with ...

Error encountered when retrieving WordPress posts through GraphQL in Next.js due to an invalid `<Link>` containing a `<a>` child element

While integrating Wordpress posts into my Next.js application using the repository "https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress", I encountered the error message: "Error: Invalid with child. Please remove or use ." https://i.ss ...

Floating images of varying sizes using a combination of CSS, JavaScript, and jQuery

I am looking for a way to showcase images in a floating style, with the challenge being that there are two different image sizes, one larger than the other with the size equivalent to 4 of the smaller ones combined. Take a look at this visual example: I a ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

What is the best way to adjust the size of a div element so that it is

I am facing an issue with a table that contains a TreeView within a cell. The code snippet is shown below: <style> #leftPanel { width:60px; height:'100%'; border:1px solid red; ...

Angular AutoComplete feature does not accurately filter the list items

I need to implement an auto-complete feature for the county field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code. The first problem is that although t ...

The UI Bootstrap Datepicker requires a second click in order to update the month

I am currently using the UI Bootstrap Datepicker component. An issue arises when I try to select the next month - the datepicker itself updates correctly, but the displayed month name does not change (refer to picture 1 and 2). Interestingly, after select ...

Distinguishing the Mouse Wheel Event

Take a look at this code snippet: <script type="text/javascript"> var scrollFunc = function(e) { var direct = 0; e = e || window.event; if(e.wheelDelta) {//IE/Opera/Chrome userMouse(e.wheelDelta); } else if(e.detail) {//Fire ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

ReactJS - Experiencing an abundance of re-renders in Protected Route

I have recently started working with React and encountered an issue with my Protected routes. They are functioning perfectly on my local machine but throwing errors on the server. You can see the error https://i.sstatic.net/l6dZW.png Below is my code: Pr ...