5

I have simple vuejs application. In the main.js I have something like:

import Vue from "vue";
import App from "./App.vue";
import router from "./router/routes";
import store from "./store/root";
import vuetify from "./plugins/vuetify";
import { RootActions } from "./constants";
import axios from "axios";

axios.get("https://api.github.com/users/mzabriskie").then(function(response) {
  console.log({ headers: response.headers });
});

In the chrome console log I got these:

enter image description here

However in https://runkit.com/greenlaw110/5e92363de9be35001ab0481e with exactly the same code, I have much more headers printed out:

enter image description here

Question:

  1. Why there is such a big difference between axios running in vuejs and a pure nodejs environment?
  2. What I really want is to get the Authorization header of the response in my VueJs application, is this really doable in any way? (Note I have already put Authorization in the Access-Control-Expose-Headers of the response to preflight request

Refer:

Gelin Luo
  • 14,035
  • 27
  • 86
  • 139

3 Answers3

6

All right, so here is the problem, the Access-Control-Expose-Headers must also be presented in the headers of response to non prefight reqeust. After I exposed this headers to all response, I can get access to the Authorization header in my vuejs app.

Gelin Luo
  • 14,035
  • 27
  • 86
  • 139
6

In the case of CORS requests, browsers can only access a few response headers by default, which are: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, Pragma

All the headers will be shown in the browser, but the client code won't be able to access these headers.

If you would like your client code to be able to access other headers (example: Token), then we need to set the Access-Control-Expose-Headers header on the server, like shown below

Access-Control-Expose-Headers: Token

In the browser API response will show all headers we need enter image description here

But the code won't be able to access the headers.

Before setting the exposed headers enter image description here

After setting the exposed headers on the server. The headers will show same in browser, but in addition browser/client code will be able to access the headers(Token) enter image description here

This answer is based on the answer provided by Nick Uraltsev at https://stackoverflow.com/a/37931084/4337125

Rajeshwar
  • 2,290
  • 4
  • 31
  • 41
1

At your app under cors ou need to enable Access-Control-Expose-Headers

example

nestjs backend app

app.enableCors({
    exposedHeaders: 'session-id'
  });

Now your client app will be able to access that response header