Adriel Kirch
Adriel Kirch

Reputation: 171

Can't connect front-end (vue) to API (nodeJS), using nginx, EC2 AWS 20.04 Ubuntu

I want to set up web servers. First I chose NodeJS with Express for backend, listening in port 3002.

app.js listening at port 3002

Ok, next I set up ubuntu firewall allowing port 3002. Then I've tested with curl a login Endpoint to be sure that backend is working fine;

curl -d '{"email":"[email protected]","password":"{{mypass}}"}' -H 'Content-Type: application/json' http://{{my-ip}}:3002/user/login 

then I got a token response, therefore API is working fine as expected.

Ubuntu firewall, pm2 start app.js, curl API request

Then I moved to front-end (vueJS), cloned vue repository, then I ran:

sudo npm i
sudo npm run build

I installed Nginx and move dist folder (vue build files) to default nginx folder "/var/www"

and renamed package:

sudo mv ./dist ./html

Then I set up nginx config at:

sudo nano /etc/nginx/sites-availabe/default
    server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;

        server_name _;

         location /api/ {
        proxy_pass http://{{my-ip}}:3002;
        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;
         }

}
sudo netstat -plant | grep 80
sudo systemctl stop apache2
sudo nginx -t
sudo systemctl start nginx

It should work fine but when I send a login response in the front-end, happens a 404 to my /api/, I even changed the base url to http://localhost:3002 but din't work as well. What should I do ? I don't know how to send a request in front-end, but curl works fine. Any tips?

Sending request to API with AXIOS, 404 NOT FOUND

AWS Security groups

Upvotes: 1

Views: 814

Answers (1)

Adriel Kirch
Adriel Kirch

Reputation: 171

I could solve the problem with API connection, using this Nginx configuration at /etc/nginx/sites-available/default

server {
  listen 80 default_server;
  server_name _;

  # front end
  location / {
    root /myprojects/front-end/dist;
    try_files $uri /index.html;
  }

  # node api reverse proxy
  location /api/ {
    proxy_pass http://localhost:3002/;
  }
}

This is the right away to use nodeJS as a proxy reverse server

Upvotes: 2

Related Questions