简体   繁体   中英

CORS problem with Nginx and NodeJS Express

I have CORS problem that did not exist until today morning. It happened probably after I updated my nginx on my Ubuntu server. I've always had in my express server the following code:

    this.express.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
      res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization"
      );
      next();
    });
  }

And it worked perfectly. Now suddenly I get prerequest error, as you can see here. The weird thing is - you need to refresh multiple times, eventually you'll get it. It's like 20% of the time, and the other 80% it works fine. https://my.treedis.com/public/asset/jtmDerKhYqV

My nginx configuration is as follows:

      location / {
                proxy_pass http://localhost:5030;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
}

For example firs time i tried to fetch and it failed due to CORS:

提取失败

And then another time I tried actually worked, same resource:

获取作品

I see Access-Control-Allow-Origin: * on your responses, when they work, but your socket.io thing is returning an invalid HTTP response more than half the time for me.

I suspect the "CORS error" you're seeing is on an HTTP error page, and not the resources you think you're serving up. Hit the "failing" URL directly and you'll see what I mean.... I get mostly 500 errors and this:

Secure Connection Failed

An error occurred during a connection to api.treedis.com. PR_END_OF_FILE_ERROR

The page you are trying to view cannot be shown because the authenticity of the received data could not be verified. Please contact the website owners to inform them of this problem.

The problem it seemed, was not related to CORS at all. It was socket.io creating too many workers on nginx, which resulted in endless errors. This is why it worked for some times, but on other time it didn't. a look into /var/log/nginx/error.log gave me the solution, so I increased the workers to 20000 using worker_connections 20000;

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