Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cors error: No 'Access-Control-Allow-Origin' header apollo-server-express

I create a project using apollo express server, apollo client 3.0. I get a cors error on the image upload side. my server side is like this.

Note : It loads images that are like 1 kb. but every image with a high kb error gives cors errors. sometimes uploads half the picture.

images are uploaded to s3.

Note 2: localhost also works with no errors.

I am using client side apollo-upload-client for upload. There is no cors setting on the client side.

I tried origin on url for cors option but it still didn't work.

const http = require("http");
const express = require("express");
require("dotenv").config();
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const { PubSub } = require("apollo-server");
const { ApolloServer } = require("apollo-server-express");
const { importSchema } = require("graphql-import");
const { GraphQLUpload, graphqlUploadExpress } = require("graphql-upload");
const GraphQLJSON = require("graphql-type-json");
const cors        = require("cors");
const bodyParser = require('body-parser')

// RESOLVERS
const resolvers = require("./graphql/resolvers/index");

const resolveFunctions = {
  JSON: GraphQLJSON,
  Upload: GraphQLUpload
};

// models

const Admin = require("./models/Admin");
const Customer = require("./models/Customers");

const pubsub = new PubSub();
const app = express();

var corsOptions = {
  origin: '*',
  credentials: true
};

// SCHEMA
const server = new ApolloServer({
  cors: corsOptions,
  typeDefs: importSchema("./graphql/schema.graphql"),
  resolvers,
  resolveFunctions,
  context: ({ req }) => ({
    Admin,
    Customer,
    pubsub,
    activeAdmin: req ? req.activeAdmin : null
  })
});


// DB
mongoose
  .connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => console.log("Connected to MongoDB"))
  .catch(e => console.log(e));



app.use(async (req, res, next) => {
  graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 });
  const token = req.headers["authorization"];
  if (token && token !== "null") {
    try {
      const activeAdmin = await jwt.verify(token, process.env.SECRET_KEY);
      req.activeAdmin = activeAdmin;
    } catch (e) {
      console.log("ERROR", e);
    }
  }
  next();
});

server.applyMiddleware({ app, cors: corsOptions});
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

httpServer.listen(process.env.PORT || 4004, () =>
  console.log(
    `🚀 Server ready at http://localhost:4004${server.graphqlPath}`
  )
);

when I try to upload an image, error;

Access to fetch at 'https://adminurl.herokuapp.com/graphql' from origin 'https://clienturl' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am using heroku, heroku error

2020-11-08T02:51:30.233151+00:00 heroku[router]: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/graphql" host=****domain**** request_id=d4db3170-15c4-41d5-81cf-83b42552d90a fwd="194.54.28.40" dyno=web.1 connect=1ms service=340ms status=503 bytes=386 protocol=https
like image 217
cnsvnc Avatar asked Apr 09 '26 04:04

cnsvnc


1 Answers

change apollosServer cors to false

  apolloServer.applyMiddleware({ app, cors: false })

and add your config in app.use:

app.use(cors(corsOptions))
like image 125
Carlos Henrique Avatar answered Apr 10 '26 17:04

Carlos Henrique



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!