"CORS header access control allow origin missing" Code Answer’s
If you are facing an issue Reason: CORS header 'Access-Control-Allow-Origin' missing, first, you need to understand what went wrong.
The issue of missing header 'Access-Control-Allow-Origin' verifies whether the resources have been retrieved by the content operating system or not. This error arises when a website or app script tries to use a resource that is not available for that request which is coming from the script of different subdomains. this violates the same-origin policy
There is a solution, if you can control and manage the server, you may add the Access-Control-Allow-Origin header's value before the requesting website.
cross origin even with allow header
header('Access-Control-Allow-Origin: http://localhost:8100');
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Accept-Language, X-Authorization");
header('Access-Control-Max-Age: 86400');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
// The request is using the POST method
header("HTTP/1.1 200 OK");
return;
}
Reason: CORS header 'Access-Control-Allow-Origin' missing
const app = express();
// CORS configuration
const corsOptions = {
origin: 'http://localhost:3000',
credentials: true
}
// The following is not needed, CORS middleware will be applied
// using the Apollo Server's middleware API (see further below)
// app.use(cors(corsOptions))
// Setup JWT authentication middleware
app.use(async (req, res, next) => {
const token = req.headers['authorization'];
if(token !== "null"){
try {
const currentUser = await jwt.verify(token, process.env.SECRET)
req.currentUser = currentUser
} catch(e) {
console.error(e);
}
}
next();
});
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({ Property, User, currentUser: req.currentUser })
});
// There is no need to explicitly define the 'path' option in
// the configuration object as '/graphql' is the default endpoint
// If you planned on using a different endpoint location,
// this is where you would define it.
server.applyMiddleware({ app, cors: corsOptions });
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
})
Keep in mind that if you use the wildcard to provide access to all sites to a private API, you are making a mistake.
If you make a CORS request without using * wildcard, the value of the request's Origin header will be read by the server, and create Access-Control-Allow-Origin from that value. Then Vary: Origin header is created to show that some headers are set dynamically depending on the origin.