简体   繁体   中英

CORS issue fetching data with WPGraphQL and Next.JS

I have created a Next.js app using Wordpress as a CMS and WPGraphQL to fetch data. I have created apollo-client the following way:

  uri: process.env.NEXT_PUBLIC_WP_API_URL,
  headers: {
    'Authorization': process.env.NEXT_PUBLIC_WP_AUTHORIZATION,
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': 'http://localhost:3000/',
    'Access-Control-Allow-Credentials': true,    
  },
  credentials: 'include',
  fetchOptions: {
    mode: 'no-cors'
  }
})
const client = new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache()
});

I can fetch data using getStaticProps and getServerSideProps with or without token but when trying with useQuery and a token it doesn't work: I get the data logged in the terminal and my Chrome.networks shows a CORS issue. Anyone had experienced it before?

CORS restrictions are executed solely by your browser. That's why you don't see any issues in queries run on the server, but in the browser is expecting the response to contain the proper headers and if not the response is blocked for reaching the application, what you are currently doing is setting the header is your request but there is nothing to ensure those headers are passed to the response.

I recommend installing the WPGraphQL CORS plugin and configuring it like in the screenshot below.

在此处输入图像描述

This will make it so localhost:3000 is properly applied to the 'Access-Control-Allow-Origin' header for GraphQL responses for requests sent from http://localhost:3000 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM