Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios - Uncaught (in promise) Error: Request failed with status code 500

I have written code for adding new articles but the Axios post request is not going through, the error I am getting is : Failed to load resource: the server responded with a status of 500 (Internal Server Error) createError.js:17 Uncaught (in promise) Error: Request failed with status code 500 at createError (createError.js:17) at settle (settle.js:19)

I have compared it with a similar project to compare which looks fine.

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

Database model

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

like image 532
Kunal Rai Avatar asked Jun 02 '19 21:06

Kunal Rai


People also ask

How to handle Axios error with promise chaining?

As Axios requests is a promise-based API, it lets you perform promise chaining by providing then () and catch () function. As a matter of fact, you can easily handle Axios error via the catch () function. See the code below:

Why can't I see the first request in Axios?

This is not an issue with Axios. When entering the URL directly in the browser, your browser adds a bunch of headers. To see them, open your browser dev tools, under the "network" tab, refresh and the first request will be the one you are interested in.

What is Axios request in JavaScript?

In JavaScript, Axios is a promise-based API, which is basically a JavaScript library. It is mainly used to make HTTP requests from Node and is also used in front-end applications. As Axios requests is a promise-based API, it lets you perform promise chaining by providing then () and catch () function.

Why am I getting a 5xx error code on Axios?

Once again, if you’re getting a 5xx error code, it’s due to your backend code. If it’s different from typing the URL by hand in the browser, check your backend code regarding request headers, cookies, etc. This has nothing to do with Axios.


1 Answers

Make sure that you are using the same request method on both client and server side (e.g post-post or get-get), I face same issue with same error when the method was not same in both side, else the below error will raise

Error: Request failed with status code 500 at createError 
like image 96
Feras Avatar answered Sep 24 '22 11:09

Feras