You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vue+TypeScript环境下,如何将Razor获取的access_token传入Axios设置全局请求头

How to Pass Access Token from Razor to TypeScript for Axios Defaults

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 global block ensures TypeScript doesn't throw errors about the global window variable. We use string | null to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:21:21