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

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

I’m using Axios 0.19.2. I added @konstantinblaesi ‘s solution:

Another option

/**
 * Whenever error.message is accessed we want to se the full API error message (JSON) if it's present
 * not just some generic http status code + message
 * see https://github.com/axios/axios/issues/960 for context
 *
 * @param axios
 */
export function extractAPIErrorResponse(axios: AxiosInstance) {
    axios.interceptors.response.use(undefined, function (error: AxiosError) {
        (error as any).originalMessage = error.message;
        Object.defineProperty(error, "message", { get: function () {
            if (!error.response) {
                return (error as any).originalMessage;
            }
            return JSON.stringify(error.response.data);
        }});
        return Promise.reject(error);
    })
}

This worked for me, thanks so much @konstantinblaesi ! I don’t understand why Axios’s default behavior isn’t like this — the standard behavior is to drop the «message» part of the original error, which I would think is the most important part!

Just to be clear, in my app, my server is returning a 400 error (which should be a response):

% curl -X POST http://my-server/api -d '{"foo": "bar"}'
{"status": 400, "message": "missing param XYZ"}

and without this fix, I get from Axios an error object that contains only name, stack, config (which has the original request), and no «response». But with this fix the error contains the correct message property from the server.

As for why there is no «response» property without this fix, it seems to be related to settle in axios.js around line 1171:

        module.exports = function settle(resolve, reject, response) {
          var validateStatus = response.config.validateStatus;
          if (!validateStatus || validateStatus(response.status)) {
            resolve(response);
          } else {
            reject(createError(
              'Request failed with status code ' + response.status,
              response.config,
              null,
              response.request,
              response
            ));
          }
        };

and you can see it doesn’t pass through response.message when creating the error. In addition, in my app I don’t see the response in error.response, there’s no such property — I don’t understand that. But anyway the above fix works for me.

In spa development with Go and Vue, I got two 500 errors when checking the operation.

spread.js: 25 GET http://127.0.0.1:8080/fetchAllProducts 500 (Internal Server Error)
(anonymous) @ spread.js: 25
e.exports @ spread.js: 25
e.exports @ spread.js: 25
Promise.then (async)
r.request @ spread.js: 25
r.<computed>@ spread.js: 25
(anonymous) @ spread.js: 25
doFetchAllProducts @ vueProduct.js: 57
boundFn @ vue.js: 197
created @ vueProduct.js: 50
callHook @ vue.js: 2895
Vue._init @ vue.js: 4547
Vue $3 @ vue.js: 4646
(anonymous) @ vueProduct.js: 1
Uncaught (in promise) Error: Request failed with status code 500
    at e.exports (spread.js: 25)
    at e.exports (spread.js: 25)
    at XMLHttpRequest.l.onreadystatechange (spread.js: 25)
e.exports @ spread.js: 25
e.exports @ spread.js: 25
l.onreadystatechange @ spread.js: 25
Promise.then (async)
doFetchAllProducts @ vueProduct.js: 58
boundFn @ vue.js: 197
created @ vueProduct.js: 50
callHook @ vue.js: 2895
Vue._init @ vue.js: 4547
Vue $3 @ vue.js: 4646
(anonymous) @ vueProduct.js: 1

Corresponding source code

new Vue ({{
    // In the "el" property, define the location that reflects the Vue display = HTML element selector (id)
    el:'#app',
    // When you change the value of a property of the data object, the view reacts and updates to match the new value
    data: {
        // Product information
        products: [],


        // Product name
        productName:'',
        // Note
        productMemo:'',
        // Product information status
        current: -1, -1,
        // Product information status list
        options: [
            {value: -1, label:'all'},


            {value: 0, label:'not purchased'},


            {value: 1, label:'purchased'}
        ],,


        // true: Entered/false: Not entered
        isEntered: false
    },


    // Calculated properties
    computed: {
        // Display the status list of product information
        labels () {
            return this.options.reduce (function (a, b) {
                return Object.assign (a, {[b.value]: b.label})
            },

 {})
        },


        // Return the product information to be displayed
        computedProducts () {
          return this.products.filter (function (el) {
            var option = this.current<0? true: this.current === el.state
            return option
          },

 this)
        },


        // Check the input
        validate () {
            var isEnteredProductName = 0<this.productName.length
            this.isEntered = isEnteredProductName
            return isEnteredProductName}
    },


    // Processing when creating an instance
    created: function () {
        this.doFetchAllProducts ()
    },


    // Method definition
    methods: {
        // Get all product information
        doFetchAllProducts () {
            axios.get ('/ fetchAllProducts')
            .then (response =>{
                if (response.status! = 200) {
                    throw new Error ('response error')
                } else {
                    var resultProducts = response.data
                    // Set the product information obtained from the server in data
                    this.products = resultProducts
                }
            })
        },


        // Get one product information
        doFetchProduct (product) {
            axios.get ('/ fetchProduct', {
                params: {
                    productID: product.id
                }
            })
            .then (response =>{
                if (response.status! = 200) {
                    throw new Error ('response error')
                } else {
                    var resultProduct = response.data
                    // Get the index of the selected product information
                    var index = this.products.indexOf (product)
                    // You can use splice to reactively change the elements of an array of data properties
                    this.products.splice (index, 1, resultProduct [0])
                }
            })
        },


        // Register product information
        doAddProduct () {
            // Parameters to send to the server
            const params = new URLSearchParams ();
            params.append ('productName', this.productName)
            params.append ('productMemo', this.productMemo)
            axios.post ('/ addProduct', params)
            .then (response =>{
                if (response.status! = 200) {
                    throw new Error ('response error')
                } else {
                    // Get product information
                    this.doFetchAllProducts ()
                    // Initialize the input value
                    this.initInputValue ()
                }
            })
        },


        // Change the status of product information
        doChangeProductState (product) {
            // Parameters to send to the server
            const params = new URLSearchParams ();
            params.append ('productID', product.id)
            params.append ('productState', product.state)
            axios.post ('/ changeStateProduct', params)
            .then (response =>{
                if (response.status! = 200) {
                    throw new Error ('response error')
                } else {
                    // Get product information
                    this.doFetchProduct (product)
                }
            })
        },


        // Delete product information
        doDeleteProduct (product) {
            // Parameters to send to the server
            const params = new URLSearchParams ();
            params.append ('productID', product.id)
            axios.post ('/ deleteProduct', params)
            .then (response =>{
                if (response.status! = 200) {throw new Error ('response error')
                } else {
                    // Get product information
                    this.doFetchAllProducts ()
                }
            })
        },


        // Initialize the input value
        initInputValue () {
            this.current = -1
            this.productName =''
            this.productMemo =''
        }
    }
})
package controller
import (
    // String and basic data type conversion package
    strconv "strconv"
    // Gin
    "github.com/gin-gonic/gin"
    // Entity (corresponds to a row in a database table)
    entity "github.com/noa-1129/golang_spa/models/entity"
    // Module for DB access
    db "github.com/noa-1129/golang_spa/models/db"
)
// Define the purchase status of the item
const (
    // Not Purchased not purchased
    NotPurchased = 0
    // Purchased is purchased
    Purchased = 1
)
// FetchAllProducts gets all product information
func FetchAllProducts (c * gin.Context) {
    resultProducts: = db.FindAllProducts ()
    // Return JSON for access to URL
    c.JSON (200, resultProducts)
}
// FindProduct gets the product information of the specified ID
func FindProduct (c * gin.Context) {
    productIDStr: = c.Query ("productID")
    productID, _: = strconv.Atoi (productIDStr)
    resultProduct: = db.FindProduct (productID)
    // Return JSON for access to URL
    c.JSON (200, resultProduct)
}
// AddProduct registers the product in the DB
func AddProduct (c * gin.Context) {
    productName: = c.PostForm ("productName")
    productMemo: = c.PostForm ("productMemo")
    var product = entity.Product {
        Name: productName,
        Memo: productMemo,
        State: Not Purchased,
    }
    db.InsertProduct (&product)
}
// ChangeStateProduct changes the state of product information
func ChangeStateProduct (c * gin.Context) {
    reqProductID: = c.PostForm ("productID")
    reqProductState: = c.PostForm ("productState")
    productID, _: = strconv.Atoi (reqProductID)
    productState, _: = strconv.Atoi (reqProductState)
    changeState: = NotPurchased
    // If the product status is not purchased
    if productState == NotPurchased {
        changeState = Purchased
    } else {
        changeState = NotPurchased
    }
    db.UpdateStateProduct (productID, changeState)
}
// DeleteProduct deletes product information from DB
func DeleteProduct (c * gin.Context) {
    productIDStr: = c.PostForm ("productID")
    productID, _: = strconv.Atoi (productIDStr)
    db.DeleteProduct (productID)
}

What I tried

・ Copy and paste of existing code

throw new Error ('response error')

.catch (error =>{
      console.error (error);

Try changing to

Supplementary information (FW/tool version, etc.)

・ Go version go1.15.2 darwin/amd64

・ [email protected]

Распознавание ошибок — обычное дело для программистов и веб-мастеров, самостоятельно прописывающих программные коды для своих ресурсов. Но порой с сообщением Error сталкиваются обычные пользователи, не имеющие даже приблизительного понятия о том, как быть в сложившейся ситуации. И возникает ступор: что делать? То ли свои действия исправлять, то ли вызывать специалистов, то ли технику уже на свалку везти?

Ошибка Uncaught (in promise) может появляться при работе с JavaScript, браузерами, приложениями и даже мессенджерами. Для понимания причины значение имеет характеристика конкретного сбоя, выводимая после Error.

В любом случае, это ошибка, возникшая в кодировке асинхронной операции с использованием функции обратного вызова. Снижая производительность кода до нуля, формально она не является критичной и, при распознавании, легко устраняется. Однако диагностировать причину бывает крайне трудоемко — именно на это указывает термин Uncaught (“необработанная”). И разобраться с возникающей проблемой по силам только грамотному и внимательному мастеру. Новичку же лучше обратиться за подсказкой к более опытным коллегам.

Для решения проблемы разработчику, как правило, предстоит вручную перебирать все варианты, которые способны вызвать несоответствие и сбой, устраняя конфликт между поставленной задачей и возможностью ее исполнения.

На практике промисы создаются как раз для того, чтобы перехватить ошибку, понять, на каком именно участке кода она возникает. Если бы не использовался Promise, команда просто оставалась бы без исполнения, а пользователь пребывал в неведении: почему та или иная функция не срабатывает? Очевидно, что информирование существенно упрощает задачу и сокращает время на реставрацию процесса.

При определении ошибки, перебирая цепочки, находят функцию, нарушающую логику. Ее обработка приводит к восстановлению работы системы. По сути, promise — это объект, не идущий в систему, а возвращающий в исходную точку сообщение о том, насколько удачно прошла операция. Если же произошел сбой — то какова его вероятная причина.

В то же время многократное использование промисов, связанное с ожиданием ответа, замедляет работу ресурса, утяжеляет его. Поэтому злоупотреблять удобной конструкцией не следует, как бы ни хотелось. Решение заключается в том, чтобы выбрать наиболее важный (или наиболее уязвимый) связующий блок, и именно на него установить необходимый код промис.

Работа по диагностике и обработке ошибок

Собственно, работа по диагностике и обработке ошибок, возникающих при создании сайтов, приложений или даже текстов в редакторе, почти всегда идет по тому же алгоритму: простым перебором исключаешь ошибочные варианты, один за другим.

Наглядный тому пример — поиск ответа на вопрос, почему перестали работать сочетания клавиш Ctrl+C и Ctrl+V. Комбинации “горячих клавиш” могут отказаться реагировать на нажатие из-за заражения вирусом, загрязнения клавиатуры, целого ряда других факторов. Тестируя их один за другим, раньше или позже непременно выйдешь на истинную причину — и тогда уже сможешь ее устранить.

Аналогично необходимо действовать при возникновении ошибки Uncaught (in promise): проверяя строчку за строчкой, каждый показатель, находить неверное значение, направляющее не туда, куда планировалось, переписывать его и добиваться намеченной цели.

Если вы не являетесь разработчиком, не создаете авторских приложений, не владеете профессиональным языком и никогда не касались даже близко программных кодов, но столкнулись с ошибкой Uncaught (in promise), прежде всего проверьте технику на присутствие вирусов. Запущенный злоумышленниками вредитель мог покалечить вашу систему в своих интересах. Второй шаг — попытка восстановления системы в точке, где она благополучно работала ранее. Вспомните, какие обновления вы устанавливали в последнюю очередь, попытайтесь избавиться от них. Если речь не идет о создаваемой вами авторской программе, избавиться от ошибки поможет переустановка поврежденного приложения. Если не поможет и это — остается обратиться к специалисту, способному исправить кодировку. При этом знайте, что проблема — не в “железе”, а в сбое используемого вами программного обеспечения.

Понравилась статья? Поделить с друзьями:
  • Uncaught in promise error cannot find module
  • Uncaught guzzlehttp exception requestexception curl error 60 ssl certificate problem
  • Uncaught exception out of memory error
  • Uncaught exception error eperm operation not permitted
  • Uncaught error no recaptcha clients exist