简体   繁体   中英

ajax request on frontend server to api's server was blocked by browser caused different domain (api's server side config is setup properly)

I am developing app as fullstack, with architecture of frontend and backend in separate machine on production. I am using native php as web app server (frontend) and nodejs+expressjs as api server. I setup CORS to give extra security of cookies management on client. It has been tested successfully during development (same machine), but when I tried to test on production env, the request was blocked by client browser. There was no error shown by browser or api's server console (means request hasn't reached api server). But on specific developer based browser, it showed error that request blocked because of different domain. Here's my machine ip config during production test:

  1. web app server using ip: http://192.168.1.200:3000 (non https)
  2. api server using domain: https://apihost.mycompany.com , with endpoint https://apihost.mycompany.com/auth/info for testing.

And here's the code:

// WEB APP SERVER - jquery ajax request resides on php page
// // runs on machine http://192.168.1.200:3000
function getUserInfo(){
  $.ajax({
    type: "GET",
    url: `https://apihost.mycompany.com/auth/info`,
    xhrFields: { withCredentials: true },
    dataType: "json",
    success: function(response) {
      // show the page
    },
    error: function(response){
      // show error message here
    },
  });
}
// API'S SERVER express page on main page with CORS included
// runs on machine https://apihost.mycompany.com
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.options("*", function(req, res, next){
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Credentials', "true");
  res.header('Access-Control-Allow-Methods', req.method);
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Length, Content-Type, Accept, Authorization, csrf-token');
  res.send(200);
});

app.use(cors(corsOptions));
// API'S SERVER - controller to send back the respond header
// runs on machine https://apihost.mycompany.com with end point GET-https://apihost.mycompany.com/auth/info
const whiteListOrigin =  ['https://livefrontend.server.com','http://192.168.1.200:3000'];
const allowedOrigin = whiteListOrigin.includes(req.headers.origin)?reqOrigin:whiteListOrigin[0];

const whiteListReqMethods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
const allowedReqMethod = whiteListReqMethods.includes(req.method)?reqMethod:whiteListReqMethods[0];

res
  .status(statusCode)
  .header("Access-Control-Allow-Origin", allowedOrigin)
  .header("Access-Control-Allow-Credentials", "true")
  .header("Access-Control-Allow-Methods", allowedReqMethod)
  .header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, csrf-token")
  .cookie('token', token, options)
  .json({
    success: true,
    token
  });

Error message by Developer's Based Browser:

Error:
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).

I checked many pages on stackoverflow or CORS documentation for solution within few days. But haven't found the solution yet. If any of you guys ever faced similar problem with kind of above alike setup, I would glad to hear your advices. Thanks in advanced

EDITED FOR: All Errors I got on browser: 在此处输入图像描述

Try next: browse to chrome://flags/, search for "Allow invalid certificates for resources loaded from localhost" and change it to "enable". Then restart your browser.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM