Unresolved CORS Issue in Vue.js Using Axios with undefined Proxy Response

My attempt to retrieve data using a client vueJS on port 8080 from the REST API on port 3000 is resulting in a CORSE Error. Interestingly, a successful POST operation occurs without any issues. To resolve this error, I followed the instructions provided in this helpful guide: https://medium.com/js-dojo/how-to-deal-with-cors-error-on-vue-cli-3-d78c024ce8d3.

//vue.config.js
module.exports={
  devServer:{
    proxy: {
      '/teams': {
        target: 'http://192.168.70.54:3000',
        ws: true,
        changeOrigin: true,
        secure: false
      }}}}

The goal is to redirect traffic towards the port 3000 for smooth functioning.

//rest.js
function getTeams() {
  var returnVal;
  axios({
    method: 'get',
    url: REST_API + '/teams',
    responseType: 'json'
    })
    .then(function (response) {
      console.log(response.data);  //The desired data to return
      returnVal = response.data; 
    });
  console.log(returnVal);          //Always undefined
  return returnVal.data;
}

Despite printing response.data to the console, the value of returnVal remains consistently undefined. What could be the missing piece in this puzzle? Below is an overview of my network log documented in the browser.

General:
Request URL: http://localhost:8080/teams
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8080

Response Headers:
Referrer Policy: no-referrer-when-downgrade
access-control-allow-header: Origin, X-Request-With, Content-Type, Accept
access-control-allow-methods: GET, POST
access-control-allow-origin: *
connection: close
content-length: 1070
content-type: application/json
Date: Tue, 17 Dec 2019 18:57:14 GMT

Request Headers:
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Host: localhost:8080
Referer: http://localhost:8080/setup
User-Agent: Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Raspbian Chromium/74.0.3729.157 Chrome/74.0.3729.157 Safari/537.36

Answer №1

This question is quite complex and involves multiple aspects.

Let's start by examining the following code snippet:

function fetchTeams() {
  var result;
  axios({
    method: 'get',
    url: REST_API + '/teams',
    responseType: 'json'
    })
    .then(function (response) {
      console.log(response.data);  //The desired return value
      result = response.data; 
    });
  console.log(result);          //Returns undefined
  return result.data;
}

The issue here is that the axios request is asynchronous, so the second log line returns `undefined`. This order of execution is expected due to the nature of asynchronous operations.

You cannot synchronously return a value retrieved asynchronously. Even using `async`/`await` may give the illusion of synchronous behavior but it simply hides the underlying promises.

To address this, you have two options:

  1. Return a promise from `fetchTeams` function and handle the data retrieval in the calling code.
  2. If you are working within a component, set a `data` property inside the `then` callback instead of returning a value.

As for the other parts of your question, it appears that your proxy configuration is successful based on the details provided. The presence of correct data in your console suggests that the proxy is functioning correctly. However, having both CORS headers and using a proxy simultaneously is redundant. A proxy serves as an alternative to CORS, not an addition.

Regarding the previous issues with CORS requests before implementing the proxy, without more information, it is challenging to pinpoint the exact cause.

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

A more concise approach to crafting ajax requests

Lately, I've been immersed in building various web applications using php, mysql, jquery, and bootstrap. Now, I'm faced with a common issue - how to streamline my ajax queries for posting data? Writing code that is not only functional but also a ...

Advantages of placing script src tags at the top of the body versus placing them at the bottom of the body

I've heard that it's best to place the script tags right before the closing body tag. However, when I follow this advice, my angularJS expressions don't seem to compute correctly for some reason. When I place the script tags in that location ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

ExpressJS and cookies - Struggling to initialize a cookie with express-cookie

I recently followed a tutorial on YouTube (https://youtu.be/hNinO6-bDVM?t=2m33s) that demonstrated how to display a cookie in the developer tools Application tab by adding the following code snippet to the app.js file: var session = require('express- ...

Error: Selenium-Javascript tests encountering an unexpected token issue

Having worked with Selenium using Java for a long time, I decided to switch gears and start writing Selenium scripts in JavaScript. I found a helpful guide to learn JavaScript with Selenium, which you can check out here. However, when I attempted to run n ...

Having an issue with Vue.js and Firebase Storage - encountering an error stating "Uncaught TypeError: storage is not a function"

I'm currently working on a Vuejs & Firebase project where I need to upload images to Firebase storage. Despite following the documentation and tutorials, I keep encountering the same error. Uncaught TypeError: WEBPACK_MODULE_1__firebase_initializer.a ...

Squashing the `require()` method in nwJS using emberJS

I am facing an issue with my nwjs application that connects to a web address hosting an ember application. I need to access the node context within the ember application to determine the user's operating system for updating purposes. I attempted to do ...

"Invalid: string path required" (version 5.10.0)

There's this file (a large bundle of a couple of JS files) that used to work perfectly with browserify (version 5.10.0) until just recently, but now it's not cooperating. Here's the command I'm using: $ browserify index.js -o dist/out ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

In React js, I wanted to display the animation specifically on the "add to bag" button for the added item

When I click the "add to bag" button, all other buttons also display the animation. How can I make sure that only the clicked button shows the animation? Any suggestions? <Table responsive> <thead> <tr> ...

Leverage the sync function within the await .then("sync") method in JavaScript

If a synchronous function is called within the .then part of an asynchronous await .then, such as: await asyncFunc(...) .then(res => sendMSG(res)) .catch(err => next(err)); function sendMSG(res){ xyz } The sync function sendMSG i ...

Jquery failing to properly loop text effect

I attempted to continuously display text using the fadein and fadeout effects. You can see exactly what I mean in this example. Below is the jQuery code where I am trying to cycle through messages: (function() { var message = jQuery("#message_after_ ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

What is the best method for retrieving the selected itemsPerPage in Vuetify's data-table in version 2.0

Recently, I've been struggling to retrieve the selected items-per-page on a Vuetify data-table due to some recent changes. I came across this helpful example: How to set initial 'rows per page' value in Vuetify DataTable component? Here is th ...

"Enhance your client-side PDF capabilities with the pdfMake plugin, offering support for multiple languages

I am in search of a plugin that can convert HTML content into a PDF format and is compatible with javascript/jQuery/AngularJS. It must also provide multilingual support. I have experimented with the following two plugins, but encountered limitations with ...

Automatically identifying cloud functions ready for deployment with the gcloud command line interface

When utilizing Firebase tools, the deployment process is streamlined with auto-detection of available functions by issuing the command: firebase deploy --only functions However, for more extensive control over environment variables and VPC connectors, we ...

Using Selenium to assign properties to JavaScript Objects

I have a JavaScript Object that needs to be set using Selenium WebDriver. var examplePlayResponse = { "prizeIndex" : 1, "mode" : "NORMAL", "id" : "abc123", "version" : "1.0", "gameCode" : "xyz789", "randomSeed" ...

Tips for choosing the default tab on Bootstrap

I have a question about an issue I am facing with my Angular Bootstrap UI implementation. Here is the code snippet: <div class="container" ng-controller='sCtrl'> <tabset id='tabs'> <tab heading="Title1"> ...