DEV Community

SIC
SIC

Posted on • Updated on

401 Error in Wordpress Plugin

When I attempt to call REST api in wordpress plugin.
For example mysite.com/wp-json/pap/v1/pixels, then I get 401 error.
So I add define( 'WP_ENVIRONMENT_TYPE', 'local' ); in wp_config.php.
then add application key value and copy the api key.
then add header as 'Authentication', 'Bearer '.
But I still get error.

import React, { useState, useEffect } from 'react';
import { render } from '@wordpress/element';

// Define the colors array
const colors = [
'#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF',
'#000000', '#FFFFFF', '#808080', 'transparent'
];

// Define the base URL
const baseUrl = 'https://localhost/mysite'; // Change this to your actual WordPress site URL

// Define your API key
const apiKey = '4w5vhI8thAHiV4iuZqxWQ3Zz';

// Define the PixelArtApp component
const PixelArtApp = () => {
// Define state variables
const [selectedColor, setSelectedColor] = useState(colors[0]);
const [pixels, setPixels] = useState(Array(256).fill('transparent'));
const [hasChanged, setHasChanged] = useState(false);
const [isDrawing, setIsDrawing] = useState(false); // Track drawing state

// Load saved pixel data from the server on component mount
useEffect(() => {
    fetch(`${baseUrl}/wp-json/pap/v1/pixels`, {
        headers: {
            'Authorization': `Bearer ${apiKey}` // Include your API key in the Authorization header
        }
    })
        .then(response => response.json())
        .then(data => {console.log({...data}); /*setPixels(data)*/})
        .catch(error => console.error('Error loading pixel data:', error));
}, []);
Enter fullscreen mode Exit fullscreen mode

};

Top comments (0)