skip to Main Content

My products.dart in models folder is :

class Products {
  final String? id;
  final String? createdAt;
  final String? price;
  final String? name;
  final String? description;
  final String? color;
  final String? stock;
  final List<dynamic>? ordersList;

  const Products(
      {this.id,
      this.createdAt,
      this.price,
      this.name,
      this.description,
      this.color,
      this.stock,
      this.ordersList});

  Map<String, Object?> toJson() {
    return {
      'id': id,
      'createdAt': createdAt,
      'price': price,
      'name': name,
      'description': description,
      'color': color,
      'stock': stock,
      'ordersList': ordersList
    };
  }

  static Products fromJson(Map<String, Object?> json) {
    return Products(
      id: json['id'] == null ? null : json['id'] as String,
      createdAt: json['createdAt'] == null ? null : json['createdAt'] as String,
      price: json['price'] == null ? null : json['price'] as String,
      name: json['name'] == null ? null : json['name'] as String,
      description:
          json['description'] == null ? null : json['description'] as String,
      color: json['color'] == null ? null : json['color'] as String,
      stock: json['stock'] == null ? null : json['stock'] as String,
      ordersList: json['ordersList'] == null
          ? null
          : json['ordersList'] as List<dynamic>
    );
  }
}

My productsController.dart is

import 'dart:convert';
import 'package:front_paye_ton_kawa/config/constants/ipadress.dart';
import 'package:front_paye_ton_kawa/models/products.dart';
import 'package:http/http.dart' as http;

class ProductsController {
  Future<List<Products>> getAllProducts(final String token) async {
    String urlString = "http://localhost:3000/api/v1/products?token=$token";
    final response = await http.get(Uri.parse(urlString));
    if (response.statusCode == 200) {
      // La requête a réussi
      var products = <Products>[];
      for (var product in json.decode(response.body)) {
        products.add(Products.fromJson(product));
      }
      return products;
    } else {
      // La requête a échoué
      throw Exception(
          "La requête a échoué avec le code d'erreur: ${response.statusCode}");
    }
  }

  Future<Products> getProductsById(
      final String idProduct, final String token) async {
    String urlString =
        "http://localhost:3000/api/v1/products/$idProduct?token=$token";
    final response = await http.get(Uri.parse(urlString));
    if (response.statusCode == 200) {
      // La requête a réussi
      var product = json.decode(response.body);
      var products = Products.fromJson(product);
      return products;
    } else {
      // La requête a échoué
      throw Exception(
          "La requête a échoué avec le code d'erreur: ${response.statusCode}");
    }
  }
}

After installing dependencies with :
npm init -y
npm install express

Here is my node.js file


const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

const products = [
  {
    id: '1',
    createdAt: '2023-08-24',
    price: '199.99',
    name: 'Krups Coffee Machine',
    description: 'High-quality coffee machine by Krups.',
    color: 'Black',
    stock: '10',
    ordersList: [],
  },
  {
    id: '2',
    createdAt: '2023-08-24',
    price: '149.99',
    name: 'Philips Coffee Machine',
    description: 'Elegant coffee machine by Philips.',
    color: 'Silver',
    stock: '15',
    ordersList: [],
  },
  {
    id: '3',
    createdAt: '2023-08-24',
    price: '129.99',
    name: 'Senseo Coffee Machine',
    description: 'Compact coffee machine by Senseo.',
    color: 'Red',
    stock: '5',
    ordersList: [],
  },
];

app.get('/api/v1/products', (req, res) => {
  res.json(products);
});

app.get('/api/v1/products/:id', (req, res) => {
  const productId = req.params.id;
  const product = products.find(p => p.id === productId);
  if (product) {
    res.json(product);
  } else {
    res.status(404).json({ message: 'Product not found' });
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Running the server with node index.js I get Server is running on port 3000

Now my API is accessible at: http://localhost:3000/api/products and http://localhost:3000/api/products/:id.

I still get the error when running my application:

Exception has occurred.
_ClientSocketException (ClientException with SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 56810, uri=http://localhost:3000/api/v1/products?token=)

2

Answers


  1. Chosen as BEST ANSWER

    Changing localhost with my machine IP address make the job done, make sure also if the firewall of the laptop block request. http://localhost:3000/api/products


  2. ‘SocketException: Connection refused’ probably caused by network blocked.

    Have you been running your app on a different terminal/network? If yes:

    1. You shouldn’t configure the IP address as 127.0.0.1, which is a loopback address. It should be changed to a reachable IP address, for instance, 10.0.0.x, or a public ip address.
    2. The HTTP port should be opened with the address 0.0.0.0, not 127.0.0.1. Otherwise, a remote terminal won’t be granted access to this port."
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search