CORS error builder component from @builder.io/react in localhost

builder component from @builder.io/react doesnt’work when I try to make a request, It’s returning CORS errors. It’s working just when I use axios.

example code:

const getArticles = async () => {
try {
const response = await axios.get(https://cdn.builder.io/api/v3/content/page-article?apiKey=${process.env.NEXT_PUBLIC_BUILDER_API_KEY}&query.data.title.$options=i&&query.data.title.$regex=.*${searchTerm}.*&limit=20&omit=data.blocks);

    setSearchResults(response);
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
};

Hello @Luiz,

Are you getting the CORS error when using axios?

No, Actually when I’m using the builder component, for example:

import { builder } from ‘@builder.io/react’;

builder.get(https://cdn.builder.io/api/v3/content/pible-page-article?apiKey=${process.env.NEXT_PUBLIC_BUILDER_API_KEY}&query.data.title.$options=i&&query.data.title.$regex=.*${searchTerm}.*&limit=20&omit=data.blocks)

Hello @Luiz!

Could you share your complete code?

useEffect(() => {
const getArticles = async () => {
try {
const response = await axios.get(https://cdn.builder.io/api/v3/content/pible-page-article?apiKey=${process.env.NEXT_PUBLIC_BUILDER_API_KEY}&query.data.title.$options=i&&query.data.title.$regex=.*${searchTerm}.*&limit=20&omit=data.blocks);

    setSearchResults(response.data.results);
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
};

}, [searchTerm]);

using axios it’s ok but if use import { builder } from ‘@builder.io/react’; so I receive CORS error

the only diference is instead of use axios.get(‘…’) I trying to use builder.get(‘…’)

Hello @Luiz,

When using the builder SDK, your code would look like the below

  useEffect(() => {
    builder
      .get("page-article", {
      limit: 100,
      query: {
        'data': { 
          "$or": [ 
            { 
              "title": { "$eq": "Qwik Blog" }
            }, 
            { 
              "title": { "$eq": "Partytown blog" }
            }
          ]
        }
      } 
      })
      .toPromise()
      .then((announcementBar) => setAnnouncement(announcementBar));
  }, []);

You should not be using the endpoint like the following https://cdn.builder.io/api/v3/content/pible-page-article?apiKey=${process.env.NEXT_PUBLIC_BUILDER_API_KEY}&query.data.title.$options=i&&query.data.title.$regex=.*${searchTerm}.*&limit=20&omit=data.blocks)

In the first moment I tryed to use this way, exactly like your example @manish-sharma but I always received CORS error in localhost so I tried to use cdn link with axios to see if it will work.

Hello @Luiz!

Are you not able to get the data from the SDK call? Would you be able to share a screen recording may be?

Hello @Luiz,

Can you make sure, you are using the correct API key and call to fetch the data, I tried below and had no issue

   useEffect(() => {
     
    async function fetchContent() {
      const content = await builder
        .get("pible-page-article", {
          url: window.location.pathname
        })
        .promise();

      setContent(content);
      setNotFound(!content);

      // if the page title is found, 
      // set the document title
      if (content?.data.title) {
       document.title = content.data.title
      }
    }
    fetchContent();
  }, [window.location.pathname]);

Additionally, are you using next js or react?

Yes, I’m using the right api key, Did you try in the local environment?

I’m using next js

Hello @Luiz,

Yes, I did try using localhost and if you are using next js you can try below

import { builder, BuilderComponent } from '@builder.io/react'

builder.init('c62b6400b6304daabf5f25c1107e9986')

export const getStaticProps = async (context) => {
  // Dynamically fetch latest content from Builder.io API
  const content = await builder.get('pible-page-article', { url: context.resolvedUrl });
  return { props: { content } }
}

// View full integration and docs: https://builder.io/c/docs/developers
export default function MyComponent(props) {
  return <BuilderComponent content={props.content} model="pible-page-article" />
}

But in my page? because in the component it doesn’t work

Hello @Luiz,

Can you try the below method

Additionally, try using CORS plugins https://chromewebstore.google.com/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

My Component is already registered and this extension didn’t work :frowning:

I need to make a request to search in client side, I need to fetch some articles using a search input for example

My Component is already registered and this extension didn’t work

I need to make a request to search in client side, I need to fetch some articles using a search input for example

Hello @Luiz!

Please help with your complete component code, so that we can reproduce the issue and assist you further.

Thanks,

import React, { useState, useEffect } from ‘react’;
import { Container, Input, SearchIconSection } from ‘./styles’;
import { FontAwesomeIcon } from ‘@fortawesome/react-fontawesome’;
import { faSearch } from ‘@fortawesome/free-solid-svg-icons’;
import { builder } from ‘@builder.io/react’;
import { useRouter } from ‘next/router’;
// import axios from ‘axios’;

type Props = {
placeholder: string;
};

builder.init(process.env.NEXT_PUBLIC_BUILDER_API_KEY || ‘’);

function InputSearch(props: Props) {
const router = useRouter();

const [searchTerm, setSearchTerm] = useState(‘’);
const [searchResults, setSearchResults] = useState();

/* useEffect(() => {
const getArticles = async () => {
try {
const response = await axios.get(https://cdn.builder.io/api/v3/content/pible-page-article?apiKey=${process.env.NEXT_PUBLIC_BUILDER_API_KEY}&query.data.title.$options=i&&query.data.title.$regex=.*${searchTerm}.*&limit=20&omit=data.blocks);

    setSearchResults(response.data.results);
    return response.data.results;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
};

const delaySearch = setTimeout(() => {
  if (searchTerm.trim() !== '') {
    getArticles(searchTerm);
  } else {
    // setSuggestions([]);
  }
}, 300);

return () => clearTimeout(delaySearch);

}, [searchTerm]); */

useEffect(() => {
if (searchTerm) {
builder
.get(‘page-article’, {
limit: 100,
query: {
data: {
$or: [
{
title: { $eq: ‘dev’ }, // just for test
},
],
},
},
})
.toPromise()
.then((response) => setSearchResults(response));
}
}, [searchTerm]);

const handleSearch = () => {
router.push(/tax-pible/${searchTerm});
};

return (

<Input
type=“text”
placeholder={props.placeholder}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>

  <SearchIconSection onClick={handleSearch}>
    <FontAwesomeIcon icon={faSearch} />
  </SearchIconSection>

  {/*  <ul>
    {searchResults.length > 0 && searchResults.map(({ data }, index) => {
      console.log('ields ', data.title)
      return (
        <li key={index}>{data.title}</li>
      )
    })}
  </ul> */}
</Container>

);
}

export default InputSearch;

Hello @Luiz,

I’m not able to reproduce the issue on my end, please refer to the loom recording below