1

I am integrating Contentful as a CMS to my react web app. The npm package contentful allows accessing the content stored using createClient method. This method uses Axios to create requests to content delivery API.

client = contentful.createClient({
        space: *** ,
        accessToken:  *** 
})

// getting data 
fetchPosts = () => this.client.getEntries()

But the problem is that - I already use Axios within my app,and every request originated through my react client includes the default common header auth-token. Due to this, I get the following error for my HTTP request - Request header field auth-token is not allowed by Access-Control-Allow-Headers in preflight response.

I tried setting the whole header as an empty object and setting auth-token as undefined but it does not help because my request would still contain the key for my default header -

client = contentful.createClient({
        space: *** ,
        accessToken:  ***, 
        headers: {} 
})

// OR

client = contentful.createClient({
        space: *** ,
        accessToken:  ***, 
        headers: { 'auth-token' : undefined } 
})

I came across this post and it answers how to modify one request to not include a common header but I am not sure how I can use this to modify createClient method. Appreciate your help.

mukund
  • 553
  • 3
  • 15
  • It sounds like you might want to switch to using the GraphQL API so that you can make calls to that API using your existing axios setup? However, that needs an 'Authorization' header, so it might be that you need to refactor your axios calls to take in dynamic headers depending on which API you want to call. – whitep4nth3r Aug 04 '21 at 07:37
  • The contentful set-up works perfectly if I just delete the default header `auth-token` that I am setting inside my project. Using GraphQL just for the sake of this functionality does not make sense. – mukund Aug 04 '21 at 09:50

1 Answers1

2

Tried the following without using contentful's javascript SDK and it works :

  1. Modify the instance of Axios for that particular request to delete your default headers
  2. Access content delivery API using base (+ plain) URLs.
const url = 
      `${baseUrl}/spaces/${spaceId}/environments/master/entries?access_token=${accessToken}` ;

axios.get(url, {
      transformRequest: (data, headers) => {
          delete headers.common['auth-token'];
          return data;
   }
})
mukund
  • 553
  • 3
  • 15