Search code examples
phpangularapiapachewamp

Failed to load resource: net::ERR_CONNECTION_REFUSED // Angular and api php


I tried to get data on my database on phpmyadmin, but I get the following error

/api/list:1 Failed to load resource: net::ERR_CONNECTION_REFUSED

My project folder is in wamp64/www.

My api tree :

api/

  • .htaccess
  • connect.php
  • list.php

.htaccess

    # Remove the php extension from the filename
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# Set the headers for the restful api
Header always set Access-Control-Allow-Origin *
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

connect.php

    // db credentials
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'cars');

// Connect with the database.
function connect() {

    $connect = new PDO('mysql:host=localhost;dbname=cars;charset=utf8', DB_USER, DB_PASS, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    
    return $connect;
    
}

$con = connect();

list.php

    require 'connect.php';

$cars = [];
$sql = "SELECT id, model, price FROM cars";

if($result = $con->query($sql)) {
    
    $cr = 0;
    while($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $cars[$cr]['id']    = $row['id'];
        $cars[$cr]['model'] = $row['model'];
        $cars[$cr]['price'] = $row['price'];
        $cr++;
    }

    echo json_encode(['data'=>$cars]);
}
else {
http_response_code(404);

}

car.service.ts

    import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';

import { map } from 'rxjs/operators';

import { Car } from './car';


@Injectable({
providedIn: 'root'
})
export class CarService {
    baseUrl = 'https://localhost/api';

    constructor(private http: HttpClient) { }

    getAll() {
        return this.http.get(`${this.baseUrl}/list`).pipe(
            map((res:any) => {
                return res['data'];
            })
        );
    }
}

app.component.ts

    import { Component, OnInit } from '@angular/core';

import { Car } from './car';
import { CarService } from './car.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    cars: Car[] = [];
    error = '';
    success = '';
    title = 'cars';
    
    constructor(private carService: CarService) {
    }
        
    ngOnInit() {
    this.getCars();
    }
        
    getCars(): void {
        this.carService.getAll().subscribe(
            (data: Car[]) => {
                this.cars = data;
                this.success = 'successful retrieval of the list';
            },
            (err) => {
                console.log(err);
                this.error = err;
            }
        );
    }
}

I am little bit lost about this error because I have no more information, I don't know if I give you enough information for this, let me know if I miss something, thank's !


Solution

  • You are using https as protocol, make sure to run your apache http on port 443 or change the url in your baseUrl to use http if you want port 80 without TLS.