I am facing an issue where there is no output displayed in the body when making a request call from the VueJS Front

I'm currently working on a VueJS web application that interacts with a C# WebAPI in the background. I have successfully created an endpoint, but I am facing an issue where the body of the response is always null. While debugging in the network tab, I can see the desired message in the preview section, but I'm unable to display it on the page.

VueJS component:

<template>
    <div class="dashboard">
        <button type="button" id="get-joke" @click="fetchAPIData">Get a Joke!!</button>
        <div v-if="responseAvailable == true">
            <hr>
            <p>
                <i>{{result}}</i>
            </p>
            <hr>
        </div>
    </div>
</template>

<script>

    export default {
        name: 'Dashboard',
        props: {
            msg: String
        },
        components: {
        },
        Data() {
            result: null,
            responseAvailable: null
        },
        
        methods: {
            fetchAPIData() {
                this.responseAvailable = false;
                fetch("https://localhost:44322/api/values", {
                    "mode": "no-cors",
                    "method": "GET",
                })
                    .then(response => {
                        alert(response); //checking if i get something
                        return response.json();
                    })
                    .then(response => {
                        this.result = response.body;
                        this.responseAvailable = true;
                    })
                    .catch(err => {
                        var error = err;
                        return error;
                    });
            }
        }

    };
</script>

C# API Controller (returning a JSON string of a list of Objects) :

using System;
using Microsoft.AspNetCore.Mvc;
using MO_Backend.Services;
using MO_Backend.APIServices;

namespace MO_Backend.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly O_UserService _oUserService;
        public ValuesController(O_UserService oUserService)
        {
            _oUserService = oUserService;
        }

        // GET: api/values
        [HttpGet]
        public String Get()
        {
            OnlineCheckService occ = new OnlineCheckService(_oUserService);
            return occ.GetRobotState();
        }
    }
}

If you have any insights on what might be causing this issue or suggestions for an alternative approach, please let me know!

Answer №1

An issue arises from the no-cors mode utilized in your http request. This leads to an opaque request, resulting in you receiving a response without being able to access the data. To address this, it's essential to switch to using cors and configure the response headers in your backend system accordingly.

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

Unable to generate a fresh database entry through form submission

I have designed User and Pairings models as shown below: class User < ActiveRecord::Base enum role: [:student, :supervisor, :admin] has_many :students, class_name: "User", foreign_key: "supervisor_id" belongs_to :supervisor, ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Searching for nodes within an XML file based on line numbers in C# - a guide

I encountered an issue with the XML files below while using them in the Process. The error message I received was: [2016-06-22 19:29:53 IST] ERROR: "Line 15 column 20: character content of element "electronics" invalid; must be equal to "foods", "goods ...

Vue.js Element UI form validation - showcasing errors returned by server

Utilizing Vue.js and Element UI libraries for my current project, I have implemented front-end validation with specific rules. However, I now also require the ability to display backend errors for the current field. When the form is submitted and an error ...

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

Javascript inheritance concepts

Creating a set of classes in JavaScript to manage accounts presents a challenge for me. The main class is 'account', which serves as the parent class, while 'depositAccount' and 'savingsAccount' are its children. These classes ...

Troubleshooting: Vuetify's 'mt-32' Margin Utility Class Not Producing Desired Results

I'm currently delving into the world of vuetify and struggling with adding the mt-32 class to the v-form in my code snippet below. <template> <v-form class="mt-32"> <v-container> <v-row align="center&quo ...

Tips for accessing Ajax data within Ember computed property

I'm facing a challenge with returning data from an Ajax call in a computed property. Despite being aware of the asynchronous nature, I am unable to figure out how to do it due to the specific requirement of returning the data in an array format with o ...

"Implementing a component that triggers an event when using mapGetters on

After loading my component, I proceed to execute the following: created() { this.$store.dispatch('messages/connect'); this.$store.dispatch('messages/fetchAllMessages'); // this.$emit('set-recipient', this.chats[0]); }, ...

Steer clear of directly modifying a prop in Vue.js to prevent errors

I have developed a custom DateField component. It is functioning properly but I am encountering an error message stating Avoid mutating the prop 'value'. This error occurs when I close the menu by clicking the Cancel button or by clicking outside ...

Angular date picker

I am using a datepicker with Angular. Here is my question: Is there a way to prevent the user from manually typing in the input field? I only want to allow the user to select a date from the pop-up calendar. ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

Display icon within ng-bind-html when the value is not true

Is there a way to integrate a fontawesome icon into ng-bind-html on ui-select based on a boolean value? <span ng-bind-html="project.IsActive == false && <i class="fa fa-ban" aria-hidden="true"></i> | highlight: $select.search">& ...

There was a problem encountered while attempting to install the 'font-awesome' package

After attempting to install Font Awesome using the command: npm install --save font-awesome I encountered errors with npm: npm ERR! path C:\Users\a\Desktop\Code\faTest\node_modules\font-awesome npm ERR! code ENOENT npm ...

"Critical issue: Meta tags are not present on the dynamic pages of the NextJS

In my NextJS application, the pages are structured as follows: App --pages ----_app.js ----index.js ----company.js ----users ------[userID].js I have a dynamic page named [userID].js that retrieves the userID through the router to display information for ...

Angular: The Process of Completely Updating a Model Object

Within my application, there is an object named eventData which acts as a singleton and is injected into multiple controllers through a resolve function. This eventData contains various sets of data such as drop down list values along with the main model. ...

retrieving the value of a field within an array

Here is my code snippet: <div class="label">{{ item.data[0] }}</div> and in the view, this is what I have: { "id": 6, "firtname": "JHON ", "lastname": "SCALA", "fullname& ...

Error: Unhandled promise rejection: [object Boolean]

I am encountering an issue while trying to secure a route in my Angular application. Despite what I believe to be the correct implementation, I am facing an error message when the negative scenario is triggered: ERROR Error: Uncaught (in promise): [object ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...