Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here.

This is the code snippet from my API:

[System.Web.Http.Route("")]
[System.Web.Http.HttpGet]
public string Test()
{
    return "working";
}

In my Vue component, I have the following code:

<template>
    <div class="home">
        <router-link to="/gameType" tag="button">New Game</router-link>
        <br /><br/>
        <router-link to="/gameHistory" tag="button">Game History</router-link>
        <br /><br />
        <router-link to="/addPlayer" tag="button">Create Player</router-link>
        <router-link to="/addTeam" tag="button">Create Team</router-link>
        <div id="app"></div>
    </div>
</template>
<script>
// @ is an alias to /src
import axios from 'axios';

async function getTest() {
    const response = await axios ({
        url: "https://audaciaballapi20200911101217.azurewebsites.net/Test",
        method: "get"
    })

    alert(response.data);
}

getTest()

</script>

Issue: No alert box is popping up as expected.

Desired Outcome: An alert box should appear with the text "working".

UPDATE: PROBLEM SOLVED With guidance from a comment, I followed this tutorial: Enabling Cross-Origin Requests in Web API. Additionally, I made changes to the backend code as shown below:

[System.Web.Http.Route("test")]
        [System.Web.Http.HttpGet]
        public HttpResponseMessage Test()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("working")
            };
        }

Now, I am able to display the response data in my front end. Thank you for the help!

Answer №1

Upon examining the call, it appears that the issue is not on the Front End (FE), but rather on the Back End (BE) as it pertains to Cross-Origin Resource Sharing (CORS),

For more information on CORS and how it functions, please visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors

To enable CORS on .NET Core => How to enable CORS in ASP.net Core WebAPI

To enable CORS on .NET Framework => How to enable cross origin requests in ASP.NET MVC

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

Sending data from an AJAX POST request to a Grails Controller

Currently, I am in the process of developing a social networking platform using Grails. However, I have encountered a roadblock when it comes to allowing users on their edit profile page to input a YouTube URL into a text field. By clicking a button, a Jav ...

Error: Call stack size limit reached in Template Literal Type

I encountered an error that says: ERROR in RangeError: Maximum call stack size exceeded at getResolvedBaseConstraint (/project/node_modules/typescript/lib/typescript.js:53262:43) at getBaseConstraintOfType (/project/node_modules/typescript/lib/type ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

The ng-if directive seems to be causing issues within an ng-repeat loop when used in conjunction with bind-html

Below is the code I am using to bind html in my webpage: <div bind-html-compile="menuButtonView"></div> This is the code in my controller: dashboardService.getTemplateMetaData(data.templateCategory) .success(function(data) { console.lo ...

In my sequence of Promises, a "reject is not defined" error led to the rejection of a Promise

In my code, I set up a chain of Promises like this: let promise = new Promise((resolve, reject) => { imgToDisplay.onload = () => { resolve(imgToDisplay.width); } }) .then((result) => { window.URL.revokeObjectURL(imgToD ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

Error: There was an issue registering the component as the target container is not recognized as a valid DOM element

Upon executing the React code below, I encountered the following error: import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <div id="root"> <h1>Hello, world!</h1></div>, document ...

Guide on using jQuery to incrementally cycle through an array using a button

I am facing an issue with iterating through an array of objects using a button. The iteration is skipping 2 on each click instead of moving to the very next record. Can someone help me troubleshoot this problem? Or suggest a better approach to iterate thro ...

Presenting JSON information in a concise and visually appealing manner

How can I extract a value from JSON data and display it in an HTML text field? The JSON data looks like this: {"name":"paul"}, but I only want to display "paul" in my text field. Here is my code in CodeIgniter PHP: $data['name'] = $this->name ...

Getting the name of parameters from Vue 3/Express

Greetings, I want to start by apologizing if the title of my question caused any confusion for those reading it. I struggled to find the right wording. The issue at hand involves a problem with sending a get request from my axios instance to my express ins ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

Showing navigation items in Vuejs based on authentication status

In my current project, I am developing a Single Page Application (SPA) using vuejs with vuetify and integrating authentication via a laravel/passport API. The challenge I'm facing is related to conditional rendering of navigation icons based on user a ...

Creating a visually appealing gantt chart in React Native using the react-google-charts library - here's how!

These are the current packages I am using: react-google-charts 1.5.5 react 16.0.0-beta.5 react-native https://github.com/expo/react-native/archive/sdk-22.0.1.tar.gz I am currently working on rendering a Gantt Chart and you can find an example here and a ...

Tips on managing ASP .NET API's HttpResponseMessage for file downloads

I came across a solution on how to download a file from an asp.net API at this link: As a result, I created an API handler with the following code: public HttpResponseMessage Post([FromBody]dynamic result) { var localFilePath = graph ...

I am experiencing issues with my local MongoDB database not properly storing data when using Express and Mongoose

I am encountering an issue where my code is functioning correctly in the console but it is not saving data to the database. Every time I restart the server, the data gets reset. While I can read data from the database without any problem, the issue arise ...

React not showing multiple polylines on the screen

I'm currently working on an application aimed at practicing drawing Kanji characters. To draw the lines, I'm utilizing svg. The issue I've encountered is that when I try to draw multiple separate lines using a 2D array of points for each lin ...

Next.js allows for dynamic page routing using the `useState` hook to redirect users

In my Next.js project, I am using the useState hook to render different components based on the button a user clicks. The main page, called account.js in the application, contains the following code: // Importing react and getting components import React f ...

What is the most effective way to communicate to my client that attempting to conceal the browser toolbar is an ill-advised decision?

One of my clients has a friend who claims to be conducting 'security testing' and insists that the PHP Zend Framework application I developed for them should implement certain browser-side features: hide the location bar, toolbar, bookmarks, me ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } expor ...

Facing a dilemma: Javascript not updating HTML image source

I am facing an issue while attempting to modify the source of my HTML image element. Despite using document.getElementId('image') in my code, I am unable to make it work as intended. Surprisingly, there are no errors displayed. Interestingly, whe ...