在Vue+TypeScript环境下,如何将Razor获取的access_token传入Axios设置全局请求头
Here's a straightforward, type-safe way to get your Razor-retrieved access token into your TypeScript code and set it as an Axios default header:
Step 1: Expose the Token from Your CSHTML File
First, use Razor to fetch the token and inject it into your page. You have two common options here:
Option A: Global Window Variable (Simplest for Client-Side Apps)
In your CSHTML file, add this script block after retrieving the token:
@{ var accessToken = await Context.GetTokenAsync("access_token"); } <script> // Make the token accessible globally window.__ACCESS_TOKEN__ = '@accessToken'; </script>
Option B: Prerender Data (For Server-Side Rendering with JavaScriptServices)
If you're using SSR, pass the token as prerender data to your Vue app:
@{ var accessToken = await Context.GetTokenAsync("access_token"); } <app asp-prerender-module="ClientApp/dist/main-server" asp-prerender-data='new { AccessToken = accessToken }' ></app>
Step 2: Access the Token in TypeScript (boot.ts)
Now, retrieve the token in your TypeScript code and configure Axios.
For the Global Window Variable Approach
First, declare the global variable to satisfy TypeScript's type checking, then set the Axios header:
// Declare the global variable so TypeScript recognizes it declare global { interface Window { __ACCESS_TOKEN__: string | null; } } import axios from 'axios'; // Set the Authorization header if the token exists if (window.__ACCESS_TOKEN__) { axios.defaults.headers.common['Authorization'] = `Bearer ${window.__ACCESS_TOKEN__}`; }
For the Prerender Data Approach
When initializing your Vue app, extract the token from the server-provided initial state (the exact property name depends on your JavaScriptServices setup):
import axios from 'axios'; import { createApp } from 'vue'; import App from './App.vue'; // Get the prerendered data (adjust the property name to match your CSHTML) const initialState = (window as any).__INITIAL_STATE__; const accessToken = initialState?.AccessToken; if (accessToken) { axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`; } createApp(App).mount('#app');
Key Notes
- Type Safety: The
declare globalblock ensures TypeScript doesn't throw errors about the global window variable. We usestring | nullto account for cases where the token might not exist. - Security: Be mindful that exposing the token in client-side code means it's accessible to the user. This is standard for SPA auth flows, but ensure your token has appropriate scopes and expiration.
- Token Refresh: If your token expires, you'll need a separate mechanism to refresh it and update the Axios header dynamically.
内容的提问来源于stack exchange,提问作者Anonymous Creator

