Axios - Uncaught (в обещании) Ошибка: запрос не выполнен с кодом состояния 500 - PullRequest
0 голосов
/ 03 июня 2019

Я написал код для добавления новых статей, но пост-запрос Axios не проходит, я получаю сообщение об ошибке: Не удалось загрузить ресурс: сервер ответил со статусом 500 (Внутренняя ошибка сервера) createError.js:17 Uncaught (в обещании) Ошибка: не удалось выполнить запрос с кодом состояния 500 при createError (createError.js: 17) при настройке (урегулирования.js: 19)

Я сравнил его с аналогичным проектом для сравнения, который выглядитштраф.

    const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const Articles = new Schema({
    title: {
        type:String
    },
    content: {
        type: String
    },
    author: {
        type:String
    },
})

module.exports = mongoose.model('Articles', Articles);

Модель базы данных

const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const PORT = 4000;
const routes = express.Router();
const Articles = require('./db');

mongoose.connect("mongodb://127.0.0.1:27017/dummies", { useNewUrlParser: true });
const connection = mongoose.connection

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

connection.on("open", () => {
    console.log("Connected to the database");
});

routes.route('/').get((req, res) => {
    Articles.find((err, articles) => {
        if (!err) { res.json(articles);}       
    }
    )
})

routes.route('/add').post((req, res) => {
    let article = new Articles(req.body);
    article.save().then(() => {
        res.status(200).json({ "article": "article saved" })
    });
})

app.use('/dummies', routes);

app.listen(PORT, () => {
    console.log('Listening...')
})

index.js

import React, { Component } from 'react';
import Navbar from './Navbar';
import 'bootstrap/dist/css/bootstrap.css';
import axios from 'axios';

class AddArticle extends Component {
    constructor(props) {
        super(props);

        this.state = {
            title:"",
            content:"",
            author:""
        };

        this.onChangeTitle = this.onChangeTitle.bind(this);
        this.onChangeContent = this.onChangeContent.bind(this);
        this.onChangeAuthor = this.onChangeAuthor.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onChangeTitle = (event) => {
        this.setState({
            title:event.target.value
        })
    }

    onChangeContent = (event) => {
        this.setState({
            content:event.target.value
        })
    }

    onChangeAuthor = (event) => {
        this.setState({
            author:event.target.value
        })
    }

    onSubmit = (event) => {
        event.preventDefault();

        let article = {
            title: this.state.title,
            content: this.state.content,
            author: this.state.author
        }

        axios.post("http://localhost:4000/dummies/add", article).then(res => {
            console.log(res.data);
        });
    }

    render() {
        return (
            <React.Fragment>
                <Navbar />
                <div>
                    <form onSubmit={this.onSubmit}>
                        <input type="text" onChange={this.onChangeTitle} value={this.state.title}/>
                        <input type="textarea" onChange={this.onChangeContent} value={this.state.content} />
                        <input type="text" onChange={this.onChangeAuthor} value={this.state.author}/>
                        <input type="submit" value="Add Article"/>
                    </form>
                </div>
            </React.Fragment>
        );
    }
}

export default AddArticle;

AddArticle.js

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...