2

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>
    );
  }
}

2
  • 1
    you have to put full url as http://localhost:3000/list or just /list I guess should work .. Commented Nov 3, 2022 at 17:09
  • Did you mean to fetch http://localhost:3000/list instead? Also you're using a timeout to set something on the response but the get function is likely synchronous meaning it will have returned before it can send the list; consider looking into promises. Commented Nov 3, 2022 at 17:09

1 Answer 1

4

You have to specify the URL as follows:

http://localhost:3000/list

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.