简体   繁体   中英

Cors + Nginx + Nodejs (VUE Frontend + Backend) doesn't work

I have my backend Nodejs running on port 23456
I have my frontend VUE running on port 8080

When i start them and when i visit my domain eg. test.dev the frontend is visible however I'm not able to login.. and it feels like it's not triggering to DB at all. The backend is starting fine, the fronend is starting fine, it just feels that they don't talk to each other since they are different ports.

For days I have been reading about this and this seems to be a CORS issue and i have tried to find right configt but since I'm noob in this nothing works.

I'm currently running NGINX and this is how my file looks like right now (etc/nginx/sites-available/test.dev.conf:

server {
listen 80;
server_name test.dev www.test.dev;
return 301 https://test.dev$request_uri;
}

server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name test.dev www.test.dev;
# Use the Let's Encrypt certificates
ssl_certificate /etc/letsencrypt/live/test.dev/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/test.dev/privkey.pem;
# Include the SSL configuration from cipherli.st
include snippets/ssl-params.conf;
location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:23456;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
}

location / {
    add_header 'Access-Control-Allow-Origin' 'http://localhost:8080' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
    add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin' always;

    proxy_pass http://localhost:8080;
    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;

}
}

I can visit test.dev and I can see the frontend, however clicking on login doesn't work. It feels like it's not connecting at all to the backend which is another port and I don't know how to get this to work..

This is the error in the console I'm getting:

控制台中的错误

Any idea how my .conf file should look like?

Thanks in advance.

I have managed to find the solution somehow.
So what i want to share is that the code above posted is correct.

Now, the solution was that I changed in the frontend VUE so that API was read from:

http://localhost:23456/api/v1

to

https://test.dev/api/v1

That's it. The login worked just find and everything works fine... Thanks for all help!

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