reactjsexpress

How do I fix my GET http://localhost:4000/contacts 404 (Not Found) error


I'm trying to get my contact list to display but I'm sure I'm doing something wrong. I just can see it.

Here is the error I'm getting

xhr.js:173 GET http://localhost:4000/contacts 404 (Not Found)

Here is my contacts-list.component.js:

import React , { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';


const Contact = props => (
    <tr>
        <td className = { props.contact.contact_completed ? 'completed' : ''}>{props.contact.first_name}</td>
        <td className = { props.contact.contact_completed ? 'completed' : ''}>{props.contact.last_name}</td>
        <td className = { props.contact.contact_completed ? 'completed' : ''}>{props.contact.email}</td>
        <td className = { props.contact.contact_completed ? 'completed' : ''}>{props.contact.mobile}</td>
        <td>
            <Link to={"/edit/" + props.contact._id}>Edit</Link>
        </td>
    </tr>
)


export default class ContactsList extends Component {

    constructor(props) {
        super(props);
        this.state = {
            contacts: []
        };
    }

    componentDidMount() {
        axios.get('http://localhost:4000/contacts')
            .then( res => {
                this.setState({
                    contacts: res.data
                })
            })
            .catch( err => console.log(err));
    }

    componentDidUpdate() {
        axios.get('http://localhost:4000/contacts')
            .then( res => {
                this.setState({
                    contacts: res.data
                })
            })
            .catch( err => console.log(err));
    }

    contactList = () => this.state.contacts.map(
        (contact, index) => <Contact contact={contact} key={index} />
    )


    render() {
        return (
            <div>
                <h3>Contacts List</h3>
                <table className="table table-striped" style={{ marginTop: 20}}>
                    <thead>
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th>Mobile</th>
                        </tr>
                    </thead>
                    <tbody>
                        { this.contactList() }
                    </tbody>
                </table>
            </div>
        )
    }
}

I think the issue is somewhere in the contacts list file or in my server.js:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const contactRoutes = express.Router();
const PORT = 4000;
let Contact = require('./contact.model');

const app = express();

app.use(cors());
app.use(bodyParser.json());

mongoose.connect(/* database url */, { useNewUrlParser: true });
const connection = mongoose.connection;

// Once the connection is established, callback
connection.once('open', () => {
    console.log("MongoDB database connection established successfully");
});

contactRoutes.route('/').get( (req,res) => {
    Contact.find((err, contacts) => {
        if(err)
            console.log(err);
        else {
            res.json(contacts);
        }
    });
});

contactRoutes.route('/:id').get((req,res) => {
    const id = req.params.id;
    Contact.findById(id, (err,contact) => {
        res.json(contact);
    });
});

contactRoutes.route('/add').post((req,res) => {
    const contact = new Contact(req.body);
    contact.save()
        .then( contact => {
            res.status(200).json({'contact': 'contact added successfully'});
        })
        .catch( err => {
            res.status(400).send('adding new contact failed');
        });
});

contactRoutes.route('/update/:id').post((req,res) => {
    Contact.findById(req.params.id, (err, contact) => {
        if(!contact)
            res.status(404).send('Data is not found');
        else {
            contact.first_name = req.body.first_name;
            contact.last_name = req.body.last_name;
            contact.email = req.body.email;
            contact.mobile = req.body.mobile;
            contact.save().then( contact => {
                res.json('contact updated');
            })
            .catch( err => {
                res.status(400).send("Update not possible");
            });
        }
    });
});

app.use('/contact', contactRoutes);

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

The error is coming from localhost:4000, but I don't understand why it's doing it. In my console, it says my backend is running.

Can anyone please help me with explaining what I'm doing wrong and help find the solution?


Solution

  • It is not about your react code. It is about your backend. Your backend may be;

    1. Not working
    2. Working in another port
    3. Does not have a GET endpoint in URL:PORT/contacts

    Copy and paste the link in your browser. If you don't get any response in the browser, then it is definitely about your backend. So, you should show your backend code.

    EDIT 1

    In your backend, you specified the route as

    app.use('/contact', contactRoutes);
    

    But, you should

    app.use('/contacts', contactRoutes);