[Vuejs]-Axios vue.js CORS Error with proxy undefined response

1👍

There’s a lot going on in this question.

Firstly, let’s focus on this bit:

function getTeams() {
  var returnVal;
  axios({
    method: 'get',
    url: REST_API + '/teams',
    responseType: 'json'
    })
    .then(function (response) {
      console.log(response.data);  //Is what I want to return
      returnVal = response.data; 
    });
  console.log(returnVal);          //Is undefined
  return returnVal.data;
}

The first log line is logging the correct value but the second log line is undefined.

This is to be expected. It has nothing to do with CORS or proxying.

The problem is that the axios request is asynchronous, so the then callback won’t be called until some point in the future. By that point the function will have returned. You should find that the log lines are being logged in the ‘wrong’ order for the same reason.

You can’t return an asynchronously retrieved value synchronously from a function. Using async/await may make it look like you can but even that is a fudge, hiding the underlying promises.

You have two options:

  1. Return a promise from getTeams. That kicks the problem of waiting up to the calling code.
  2. If you are inside a component you can set a data property inside the then callback. This is instead of returning a value.

Then we have the other parts of your question.

It would seem that you have successfully managed to configure a proxy. Difficult to be sure but from everything you’ve included in the question that seems to be working correctly. You wouldn’t be getting the correct data in your console logging if the proxy wasn’t working.

However, there are a lot of CORS headers in your response. If you’re using a proxy then you don’t need the CORS headers. A proxy is an alternative to CORS, you don’t use both.

As for why your CORS request was failing prior to using a proxy, it’s difficult to say from the information provided in the question.

Leave a comment