nuxt-modules / apollo

Nuxt.js module to use Vue-Apollo. The Apollo integration for GraphQL.
https://apollo.nuxtjs.org
MIT License
943 stars 198 forks source link

CORS error after deploying backend part in Heroku #427

Open bobbykim89 opened 2 years ago

bobbykim89 commented 2 years ago

It didn't have any error while running on the localhost but CORS error appeared after deployment. I already add cors middleware in the backend but still not doing a thing. hatecors

this is my srver.js code in backend:

const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const connectDB = require('./database')
const schema = require('./schema/index')
const auth = require('./middleware/auth')
const cors = require('cors')

const app = express()

// Connect to DB
connectDB()

// Allow cross-origin requests

app.use(
  cors({
    origin: ['https://stock-track-woad.vercel.app/', 'http://localhost:3000/'],
    credentials: true,
    methods: ['GET', 'POST', 'PUT'],
  })
)

// Apply auth check middleware
app.use(auth)

// Serve app using GraphQL
app.use('/graphql', graphqlHTTP({ schema, graphiql: true }))

const PORT = process.env.PORT || 4000

app.listen(PORT, () => console.log(`Server listening on port ${PORT}`))

this is my nuxt.config.js

buildModules: ['@nuxtjs/moment'],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/bootstrap
    'bootstrap-vue/nuxt',
    '@nuxtjs/apollo',
    '@nuxtjs/proxy',
  ],
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: process.env.BASE_URL || 'http://localhost:4000/graphql',
        httpLinkOptions: {
          headers: {
            Authorization: token ? `Bearer ${token}` : '',
          },
          mode: 'cors',
        },
        watchLoading: '~/plugins/apollo-watch-loading-handler.js',
        errorHandler: '~/plugins/apollo-error-handler.js',
        tokenName: 'apollo-token',
      },
    },
  },
  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {},
  proxy: [process.env.BASE_URL],
  env: {
    BASE_URL: process.env.BASE_URL || 'http://localhost:4000',
 }

I am still learning and feeling pretty clueless at the point. Thanks for the help!!

lsiban commented 2 years ago

I have the same issue and my guess is because the server host is not running on https and this causes cors issue because the origin and host should be both https or http. Check this link under Other possible causes include section.

Afzzal-Mahmud commented 1 year ago

Did you solve it? I am searching for the answer but found nowhere.please let me know if you solved it . Thank you

BigadG commented 6 months ago

I have the same issue and my guess is because the server host is not running on https and this causes cors issue because the origin and host should be both https or http. Check this link under Other possible causes include section.

I am DESPERATELY trying to find the solution. Did you figure it out??