Skip to content

Set API Request Token Globally

To ensure that all API requests include an authentication Token, you can override the built-in request method and dynamically set the Token before requests. This not only ensures request security but also makes Token management more centralized and consistent.

Override Built-in Request Method and Set Token

You can customize the formCreate.fetch method to automatically attach a Token to each request.

js
formCreate.fetch = (options) => {
    // Get or generate Token
    const token = 'your-auth-token'; // The token here can be obtained from Vuex, localStorage, or elsewhere


// Set request headers, attach Authorization token
    const headers = {
        ...options.headers,
        Authorization: `Bearer ${token}`,
    };


// Make request
    fetch(options.action, {
        method: options.method || 'GET', // Default request method is GET
        headers: headers,                 // Request headers including Authorization
        body: options.method !== 'GET' ? JSON.stringify(options.data) : null, // If it's POST or other methods, add request body
    })
    .then(response => response.json())  // Parse response as JSON
    .then(data => {
        if (options.onSuccess) {
            options.onSuccess(data);  // Success callback
        }
    })
    .catch(error => {
        if (options.onError) {
            options.onError(error);  // Error callback
        }
    });
};

Set Token Before Request

Using the beforeFetch hook, you can set the Token before each request is sent. The following shows how to use this hook in a Vue component:

vue
<template>
    <form-create :rule="rule" v-model:api="api" :option="options" />
</template>


<script setup>
    import { ref } from 'vue';
    const api = ref({});
    const options = ref({
        // Hook before request is sent
        beforeFetch: (options) => {
            // Dynamically set Authorization token in request headers
            const token = 'your-auth-token'; // The token here can be obtained from any storage
            options.headers = {
                Authorization: `Bearer ${token}`
            };
        }
    });
    const rule = ref([
        {
            type: 'select',
            field: 'product',
            title: 'Select Product',
            fetch: {
                action: '/api/products',
                to: 'options',
                parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
                onError: (error) => console.error('Failed to load product data:', error),
            },
        }
    ]);
</script>

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.