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
change apollosServer cors to false
apolloServer.applyMiddleware({ app, cors: false })
and add your config in app.use:
app.use(cors(corsOptions))
Try this instead of server.applyMiddleware. But I'm not sure it will solve your problem.
app.use(cors(corsOptions));
Follow simple two steps
Step 1 install the package cors
npm i cors
Step 2 Import as
const cors = require("cors");
After creation of app from express that is "const app = express();"
Paste following line
app.use(cors());
Note : if you want to configure more you can delecture corsOption object and pass to cors() as
const corsOptions = {
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
};
app.use(cors(corsOption));
Solution 2 If you are using reactjs as client side, then keep sure to set complete url path for your server where apollo server backend is running
const httpLink = createHttpLink({
uri: "http://localhost:5000/graphql",
});
if you use only http://localhost:5000/ it will throw cors error
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.