How to add CSRF Token to fetch() headers and body

    // Login user
    async login(credentials) {
        this.showLoading();
        try {
            const response = await fetch(`${this.baseURL}/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(credentials)
            });

            const data = await response.json();

            if (response.ok) {
                // Store token and user data
                localStorage.setItem(this.tokenKey, data.token);
                localStorage.setItem(this.userKey, JSON.stringify(data.user));
                
                this.showMessage('login-message', 'Login successful!', 'success');
                this.updateNavigation(true);
                this.showDashboardSection();
                return { success: true, data };
            } else {
                throw new Error(data.message || 'Login failed');
            }
        } catch (error) {
            this.showMessage('login-message', error.message, 'error');
            return { success: false, error: error.message };
        } finally {
            this.hideLoading();
        }
    }

This works in another project , but i only used the function in a PHPmaker custome page

fetch(BASE_URL + 'orderajax', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '<?= $TokenValue ?>'
        },
        body: JSON.stringify({
            category_id: category_id,
            '<?= $TokenNameKey ?>': '<?= $TokenName ?>',
            '<?= $TokenValueKey ?>': '<?= $TokenValue ?>'
        })
    })

My currrent project is an html page using fetch with phpmaker api . I can figure out how to get the tokens

  1. You simply use ew.fetch(), it is a wrapper of fetch(), it will add the CSRF token automatically if ew.TOKEN_NAME and ew.ANTIFORGERY_TOKEN exist. (They will exist if Include Common Files is enabled.)
  2. There is no need to add the token in the header.
  3. No need to use JSON.stringify() either.