apollo icon indicating copy to clipboard operation
apollo copied to clipboard

CORS error after deploying backend part in Heroku

Open bobbykim89 opened this issue 3 years ago • 3 comments

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!!

bobbykim89 avatar Feb 14 '22 04:02 bobbykim89

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.

lsiban avatar Aug 30 '22 03:08 lsiban

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

Afzzal-Mahmud avatar Mar 26 '23 21:03 Afzzal-Mahmud

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??

BigadG avatar Mar 08 '24 20:03 BigadG