Home  >  Q&A  >  body text

node.js - Issues about CORS cross-domain configuration in nginx

I recently worked on a vue project and wanted to put it on my own cloud server. The server system is centos 7. Node and nginx have been installed. However, after passing the packaged project through the nginx proxy, I found that cross-domain requests cannot be made. , so I asked Google and Baidu how to configure cors cross-domain in nginx. I tried a lot of codes, but to no avail. I hope someone can help me take a look.

nginx.conf configuration is as follows:

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  maxutian.cn www.maxutian.cn;
        root         /root/hexo/public;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
    }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

    server {
        listen       80;
        server_name  music.maxutian.cn;
        root         /root/dist;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    
    
        location / {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
    }
        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

Since there is more than one vue project in the server, a second-level domain name is set up and two servers are written. The first server is my blog, and the second server is the vue project. Is there any problem with my configuration?

迷茫迷茫2686 days ago817

reply all(3)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-12 09:26:25

    The poster needs to first understand what CORS is. It is recommended to read the following article first

    HTTP Access Control (CORS)

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:26:25

    Refer to the Zhihu column I wrote:

    https://zhuanlan.zhihu.com/p/...

    Emphasis - add_header should add always:

    add_header Access-Control-Allow-Origin * always;

    reply
    0
  • PHP中文网

    PHP中文网2017-06-12 09:26:25

    You can use nginx proxy forwarding to achieve cross-domain

    server {
        listen  80;
        server_name 127.0.0.1;
    
        location ~ /api/ {
            proxy_pass  http://127.0.0.1:8081;
            proxy_set_header Host $host:80;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

    Forward http://127.0.0.1/api/ request to http://127.0.0.1:8081

    reply
    0
  • Cancelreply