Angular通过PHP连接MySQL时遇ERR_CONNECTION_REFUSED错误求助
net::ERR_CONNECTION_REFUSED for Angular + PHP + MySQL Setup Hey there! Let's work through that frustrating connection error you're seeing. The net::ERR_CONNECTION_REFUSED message means your Angular app can't even reach your PHP backend server—this is usually a problem with your local server setup, not the database connection itself (that would throw a different error once the server is reachable). Here's how to troubleshoot step by step:
1. Make Sure Your Local Web Server is Running
First things first: Is your Apache/Nginx (from XAMPP/WAMP/MAMP or manual setup) actually up and running?
- If you're using XAMPP, open the control panel and check that the Apache module shows "Running".
- For manual server setups, verify the service is active with commands like
sudo systemctl start apache2(Linux) or checking the Services list (Windows).
If the server isn't running, start it—this is the most common cause of connection refused errors.
2. Fix Your API URL Protocol & Port
Your Angular service uses https://localhost/api, but most local dev servers don't use HTTPS by default (unless you've configured SSL certificates):
- Switch the protocol to
httpfirst:// Update baseUrl in your CityweatherService baseUrl = 'http://localhost/api'; - If you've changed the default server port (e.g., 8080 instead of 80), add it to the URL:
http://localhost:8080/api
Test this URL directly in your browser—if it doesn't load, your server or path is still misconfigured.
3. Verify Your PHP File Path
Double-check that your list.php is in the right location relative to your web server's root directory:
- For XAMPP, the root is
htdocs—so you should havehtdocs/api/list.php - Try accessing
http://localhost/api/list.phpdirectly in your browser. If you get a 404 error, your folder structure is wrong. Adjust theapifolder location or update yourbaseUrlto match the correct path.
4. Pre-Check Your Database Connection (For Later)
While this isn't causing the current connection error, once your server is reachable, you might hit database issues. Verify your PHP credentials:
- Confirm
DB_PASSmatches your MySQL root password (you have it set toxyz—is that correct?) - You can test the connection by adding a debug line to your PHP code:
$con = connect(); if ($con) { echo "Database connected successfully!"; }
Run this in your browser—if it prints the success message, your database connection is good.
Final Test Steps
- Start your web server
- Access
http://localhost/api/list.phpin your browser and confirm it returns valid JSON (or at least loads without errors) - Update your Angular
baseUrlto match the working URL - Restart your Angular dev server and test the
getAll()method again
This should resolve the connection refused error. Let me know if you hit any snags along the way!
内容的提问来源于stack exchange,提问作者SB1990

