Home > Back-end >  Fetch API cannot load localhost:3000
Fetch API cannot load localhost:3000

Time:11-04

I have an express-js server that returns an array of data. I need to make a request using the Fetch API and display this list on the screen. Now when I make a request to the server - I get an error - Fetch API cannot load localhost:3000. URL scheme "localhost" is not supported. How can I solve this problem and get the list?

// server 

const express = require('express');
const cors = require('cors')

const app = express();
app.use(cors());

app.get('/list', (req, res) => {
  const list = [{
      id: 1,
      name: "Item1",
    },
    {
      id: 2,
      name: "Item2",
    },
    {
      id: 3,
      name: "Item3",
    },
  ];


  setTimeout(() => {
    res.send(list);
  }, 2000)
});

app.listen(3000, () => {
  console.log('Server start');
});

import React, { Component } from "react";

export default class List extends Component {
  constructor(props) {
    super(props);

    this.state = {
      list: null,
    };
  }

  componentDidMount() {
    fetch("localhost:3000")
      .then((response) => response.json())
      .then((list) => {
        console.log(list);
      });
  }

  render() {
    return (
      <ul>
        {/* {this.state.list.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))} */}
      </ul>
    );
  }
}

CodePudding user response:

You have to specify the URL as follows:

http://localhost:3000/list

  • Related