I am trying implementing CORS policy on existing API server, so this is configuration :
- API server hosted at https://apihost.mycompany.com built on nodejs+express behind NGINX with proxy pass enabled.
a. Here's nginx config :
server {
listen 443 ssl;
server_name apihost.mycompany.com ;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://localhost:5000;
proxy_pass_request_headers on;
}
}
b. Express JS on index.js page :
const whiteListOrigin = ['https://livefrontend.server.com','http://192.168.1.200:3000'];
const whiteListReqMethods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
var corsOptions = {
origin: function (origin, callback) {
if (whiteListOrigin.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
methods: whiteListReqMethods,
allowedHeaders: ['Content-Type', 'Authorization', 'x-csrf-token'],
credentials: true,
maxAge: 600,
exposedHeaders: ['*', 'Authorization' ],
preflightContinue: true,
optionsSuccessStatus: 204
};
app.use(cors(corsOptions));
- Web app server as front end server hosted at http://192.168.1.200:3000 (non https) built by PHP+JQUERY and XAMPP. Here's the request code to API Server :
function getUserInfo(){
$.ajax({
type: "GET",
url: `https://apihost.mycompany.com/info`,
xhrFields: { withCredentials: true },
dataType: "json",
success: function(response) {
// show the detail user
},
error: function(response){
// show error message here
},
});
}
The browser Error message when the page doing request to API is :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://apihost.mycompany.com/auth/info. (Reason: CORS request did not succeed). Status code: (null)
When I tried to log Origin value on Express it showed me UNDEFINED. So I guess the problem is because NGINX doesn't forward the client's/browser's request header to Express (API Server). I checked lot of CORS related question on SO and haven't got solution yet. Am I missing something on this configuration? Need suggestion and solution pls. Thanks.