-3

sorry for my english. I'm trying to deploy my vue.js website on an AWS instance. I use axios to consume my nodejs APIs, but I have a problem. When accessing the browser with the public address, in axios requests if I use localhost it does not work (I get the error http://localhost:3000/categorias net::ERR_CONNECTION_REFUSED), however if I use the public address it works correctly.

Both nodejs and vuejs are running on the same EC2 instance.

I have already tried testing my API from the console with curl -X GET localhost:3000/categories and it works, but in vue.js of my EC2 instance it does not work.

In the CORS of my nodejs I have allowed http://localhost:5173, a port that corresponds to my vue.js

2
  • 1
    The host is as seen from your browser. “localhost” means your own computer. But your server isn’t running on your computer, it’s running on EC2. So yes, you need to use your EC2 instance’s address.
    – deceze
    Commented Dec 4, 2023 at 6:52
  • The typical approach to this is mode-specific environment variables defining things like API URLs. See vitejs.dev/guide/env-and-mode
    – Phil
    Commented Dec 4, 2023 at 6:58

1 Answer 1

0

When you put the localhost URL in vue.js it will not work because it's considered system localhost, not the server host. So it would be best to use an EC2 instance public IP address or point to the domain.

When you request to vue.js to the public IP of the AWS EC2 instance due to two different IP addresses like your service IP is 111.111.111.11 for accessing Vue.js frontend website and as API like 111.111.111.11:3000 Or any other port it maybe gives you CORS origin error in the browser or network API so, you need to allow origin in Nodejs code like this

app.use(cors({
   origin: ['http://111.111.111.11']
}));

OR

// All URL is allowed to access
app.use(cors({
   origin: '*' // Just For testing
}));

This way you fix the CORS origin error.

EDIT

You need to allow that port from the EC2 security group to access. If the port is not allowed in the network or security group you won't be able to access it.

You can check this link for more details How to open a web server port on EC2 instance

2
  • OP did not mention any CORS origin error
    – Phil
    Commented Dec 4, 2023 at 7:00
  • @Phil - He mentioned CORS so I added more details about CORS because API runs on a 3000 port and the service is run a different port. Commented Dec 4, 2023 at 8:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.