a year ago
I have an Express server and a client application under the example.com domain. The server is accessible via server.example.com, and the client via app.example.com.
Issue:
When trying to access the server from the published client (https://app.example.com), I get the following CORS error:
Access to XMLHttpRequest at 'https://server.example.com/users?_id=TsJYVYrudlOB0c6k0A3qosisLId2' from origin 'https://app.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What Works:
Accessing the server from a local client (running on localhost) works without any issues.
Direct requests to the server using curl return the expected response with the correct CORS headers:
* Trying 34.32.135.56:443...
* Connected to server.example.com (34.32.135.56) port 443
* schannel: disabled automatic use of client certificate
* ALPN: curl offers http/1.1
* schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.
* Closing connection
* schannel: shutting down SSL/TLS connection with server.example.com port 443
curl: (35) schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.
Setup:
Express Server Configuration:
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import http from 'http';
const app = express();
const server = http.createServer(app);
const corsOptions = {
origin: [
"http://localhost:5173",
"http://localhost:5174",
"http://localhost:5175",
"https://example.com",
"https://www.example.com",
"https://app.example.com",
],
credentials: true,
allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept"],
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
};
app.use(cors(corsOptions));
app.use(express.json());
// Add detailed logging to ensure CORS middleware is applied
app.use((req: Request, res: Response, next: NextFunction) => {
console.log('Request received:', req.method, req.url);
console.log('Origin:', req.headers.origin);
next();
});
app.use((req: Request, res: Response, next: NextFunction) => {
console.log('CORS headers after CORS middleware:', res.get('Access-Control-Allow-Origin'));
next();
});
// Example route to test CORS
app.get('/users', (req: Request, res: Response) => {
res.json({ message: 'CORS is working!' });
});
// Error handling middleware
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.error('An error occurred:', err);
res.status(500).json({ error: 'Internal Server Error' });
});
// Server listening setup
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(
`*********************************************************************** SERVER IS RUNNING ON PORT ${PORT} ***********************************************************************`
);
});
Client Code:
const baseUserPath = `${import.meta.env.VITE_PUBLIC_SERVER_BASE_URL}/users`;
useEffect(() => {
if (!auth) return;
const authStateListener = onAuthStateChanged(auth, (newAuthUserState) => {
if (newAuthUserState) {
setAuthUser(newAuthUserState);
(async () => {
try {
const response = await axios.get(baseUserPath, {
params: {
_id: newAuthUserState.uid,
},
withCredentials: true, // Tried both with and without withCredentials
});
setUser(response.data);
} catch (err: unknown) {
if (err instanceof Error) {
throw new Error(err.message);
}
throw err;
} finally {
setLoadingInitial(false);
}
})();
} else {
setAuthUser(undefined);
setUser(undefined);
setLoadingInitial(false);
}
});
return authStateListener;
}, [auth]);
Steps Taken:
Disabled Cloudflare Proxy: Disabled Cloudflare's proxy for both server.example.com and app.example.com to rule out any proxy-related issues. It has been over 72 hours since the change, so DNS propagation should not be an issue.
Testing with cURL: Direct access using curl -vk "https://server.example.com/users?_id=TsJYVYrudlOB0c6k0A3qosisLId2" results in SSL errors related to certificate revocation.
Local Access Works: When accessing the server from a local client running on localhost, the requests are successful, and CORS headers are correctly set.Checked Environment Variables: Verified that the environment variables are correctly set.
SSL Certificate Check: Verified that the SSL certificate is valid and trusted by all major web browsers.
Any suggestions on what might be causing this issue or further steps to diagnose and resolve it would be greatly appreciated.
Thank you!
1 Replies
a year ago
What is the exact value of VITE_PUBLIC_SERVER_BASE_URL
Please include the exact value as you have it in your service variables, do not substitute the domain for an example domain.