首页 > 解决方案 > 如何修复我的 GET http://localhost:4000/contacts 404(未找到)错误

问题描述

我正在尝试显示我的联系人列表,但我确定我做错了什么。我只是可以看到它。

这是我得到的错误

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

这是我的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>
        )
    }
}

我认为问题出在联系人列表文件中或我的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);
});

错误来自localhost:4000,但我不明白为什么会这样。在我的控制台中,它说我的后端正在运行。

谁能帮我解释我做错了什么并帮助找到解决方案?

标签: reactjsexpress

解决方案


这与您的反应代码无关。这是关于你的后端。您的后端可能是;

  1. 不工作
  2. 在另一个港口工作
  3. 在 URL:PORT/contacts 中没有 GET 端点

将链接复制并粘贴到浏览器中。如果您在浏览器中没有得到任何响应,那么肯定与您的后端有关。因此,您应该显示您的后端代码。

编辑 1

在您的后端,您将路线指定为

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

但是,你应该

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

推荐阅读