Post 500 internal server error axios

2 votes and 41 comments so far on Reddit

I’m trying to convert the plain text that’s entered from review with axios. However I get an error in the console log saying: POST http://localhost:8080/api/sentiment/analysis 500 (Internal Server Error) and then I console.log(error.reponse) and got this in the console after I entered the letter j into the text area.

I am trying to convert my data because when I send the data in postman I have no issue. However in the axios post I get a server 500 error and when I console.log(error.reponse) it says undefined, so I figured because in Postman I’m sending a JSON payload like «this» I should try send it that way in the axios post too.

This is my frontend

import React, {useState, useRef} from 'react';
import Axios from 'axios';
import {Button, Input} from 'antd';
import authService from '../../services/auth.service'
import authHeader from '../../services/auth-header';
import FirstReview from './FirstReview';
import { useEffect } from 'react';

const {TextArea} = Input;

const Reviews = (props) => {

    const currentUser = authService.getCurrentUser();
    const [review, setReview] = useState('');
    const [sentiment, setSentiment] = useState(0);

    const handleChange = (e) => {
        setReview(e.target.value)
    }

    const onSubmit = (e) => {
        e.preventDefault();

        const variables = {
            movieId: props.movieId,
            content: review,
            author: currentUser.id,
            reviewId: props.reviewId,
        }

        Axios.post('http://localhost:8080/api/review/addReview', variables,{ headers: authHeader()})
        .then(response=> {
            if(response.data.success) {
                setReview("")
                props.refreshFunction(response.data.result)
            } else {
                alert('Failed to save review')
            }
        })

    }
    
    useEffect(() => {
        async function fetchSentiment(review) {
        const result = Axios.post('http://localhost:8080/api/sentiment/analysis', JSON.stringify(review), {headers: authHeader()})
              .then(response => {
                  if (response.data.success) {
                      console.log('HERE',response.data)
                      // setReviewList(response.data.reviews)
                  } else {
                      alert('Error')
                  }
                  setSentiment(result.sentiment)
              })
              .catch((error) => {
                  console.log(error.response)
              })
        }
        fetchSentiment(review)
      }, [review])
  


      
    return (
        <div>
                <p>Reviews</p>
                {props.reviewList && props.reviewList.map((review, index) => (
                    (!review.responseTo &&
                    <React.Fragment key={review._id}>
                        <FirstReview review={review} movieId={props.movieId} refreshFunction={props.refreshFunctions}/>
                    </React.Fragment>
                )))}
                <form style={{display: 'flex'}} onSubmit>
                    <TextArea
                        style={{width: '100%', borderRadius: '5px'}}
                        placeholder = "leave a review"
                        value={review}
                        onChange={handleChange}
                        />
                        <Button style = {{width: '20%', height: '52px'}} onClick={onSubmit}></Button>
                </form>
        </div>
    );
};

export default Reviews

Backend

const express =  require('express');
const router = express.Router();
const getSentiment = require('../sentiment-analysis/sentimentAnalysis')

router.use(function(req, res, next) {
    res.header(
      "Access-Control-Allow-Headers",
      "x-access-token, Origin, Content-Type, Accept"
    );
    next();
});

router.post('/analysis', (req, res) => {
    const data = req.body.data
    const sentiment = getSentiment(data)
    return res.send({sentiment})
})

module.exports = router;

EDIT: This is my server.js file.

const express = require("express");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

const db = require("./app/models");
const Role = db.role;

db.mongoose
  .connect(`mongodb+srv://(databaseurl).gmvao.mongodb.net/test?retryWrites=true&w=majority`, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("Successfully connect to MongoDB.");
    initial();
  })
  .catch(err => {
    console.error("Connection error", err);
    process.exit();
  });

// simple route
app.use('/api/favourite', require('./app/routes/favourite.routes'));
app.use('/api/review', require('./app/routes/review.routes'));
app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));
// routes
// require(".app/routes/favourite.routes")(app);
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

function initial() {
  Role.estimatedDocumentCount((err, count) => {
    if (!err && count === 0) {
      new Role({
        name: "user"
      }).save(err => {
        if (err) {
          console.log("error", err);
        }

        console.log("added 'user' to roles collection");
      });

      new Role({
        name: "creator"
      }).save(err => {
        if (err) {
          console.log("error", err);
        }

        console.log("added 'creator' to roles collection");
      });

      new Role({
        name: "watcher"
      }).save(err => {
        if (err) {
          console.log("error", err);
        }

        console.log("added 'watcher' to roles collection");
      });
    }
  });
}

Mr_SC

If you have been searching the web for some information about AXIOS error messages, and would like to understand how to use them, then you have come to the right place.

TLTR; Find the code snippets in the following section

If you search the web on this topic, all you can find is:

  • catching error body using axios post
  • Unable to catch the body of error
  • JS Axios – how to get response body in event of error?
  • How to see axios error response JSON in React

The list could have gone on and on, but they all ask for the sample simple question:

How can someone get the actual error information coming from a bad request made with AXIOS.

In this post we are going to provide information on “why” so many people ask for information, and “how” this information can be found.

Why so many people ask for this

If you have ever worked with an api, you perfectly know that request not always go to plan. You hope to always get a lovely response with a status of 200, but this does not always happens.

In many instances the status of our request may return some kind of error (400, 500), and when this happens we would like to be able to have a readable error message.

axios.get('EndpointWithAuthorizedError')
    .then((response) => {})
    .catch((error) => {
        console.log(error);
    })

Enter fullscreen mode

Exit fullscreen mode

Unfortunately if the above would ever fail with a meaningful error, we would still see this within our console, as the variable passed by the catch statement seem to be of type “string”.

Error: Request failed with status code 401

Enter fullscreen mode

Exit fullscreen mode

This is actually the main reason why so many people are “forced” to ask for help.

How can we process AXIOS error message

There is actually no magic when processing the error messages. In fact, the catch is in the fact that the variable received by the catch statement seem to be a string, but in reality it is not.

The AXIOS error message can actually return 3 different structure, depending from what kind of failure it has (crazy right… I thought that too).

Error in setting up the request

This error can happen if we have made an actual mistake in setting up the AXIOS request. It could be something with the data passed, or a configuration setting.

When this happen we can actually find the information we need by accessing the message parameter of the catch.

axios.get('wrongSetup')
    .then((response) => {})
    .catch((error) => {
        console.log(error.message);
    })

//or using destructuring
axios.get('wrongSetup')
    .then((response) => {})
    .catch(({message) => {
        console.log(message);
    })

Enter fullscreen mode

Exit fullscreen mode

No response – Network Error

This scenario will take place when our request had no response at all. This can happen when the URL is incorrect, or if the receiving server is down.

When this happen we can access more information about our request bu accessing the request parameter. This will return the actual “request” information.

axios.get('network error')
     .then((response) => {})
     .catch((error) => {
         console.log(error. request );
     })
//or using destructuring
 axios.get('network error')
     .then((response) => {})
     .catch(({ request ) => {
         console.log( request );
     })

Enter fullscreen mode

Exit fullscreen mode

Request returned with an error status

This is one of the most common, or more specifically the one type of “error” that need to be manage to make sure our web applications function properly.

There are hundreds of status code differently than 200 (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status), that would fit in this category. I am going to list below the most important:

  • 400: Bad request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server error
  • 502: Bad Gateway

When any of the above happen, we would like to know more about the request. In this case there are more information provided to us: data, status, header.

axios.get('errorStatus')
     .then((response) => {})
     .catch((error) => { 
         console.log(error.response.data);  
         console.log(error.response.status);  
         console.log(error.response.headers); 
     })

//or using destructuring
 axios.get('errorStatus')
     .then((response) => {})
     .catch(({ response }) => { 
         console.log(response.data);  
         console.log(response.status);  
         console.log(response.headers);  
     })

Enter fullscreen mode

Exit fullscreen mode

With the above code, we will be able to get all the information we need about the response to our request. These includes the status code, the header and last but not least the data that the server has sent with the request.

When using any kind of API, the data parameter is going to include essential information, usually used for development purposes, but at times also good to show to the end users.

I hope to have saved you some time, and please feel free to comment, or provide suggestion to improve this post and help future readers

Я использую axios в своем приложении для отправки POST на другой сервер. Если сервер отвечает кодом с ошибкой 500, он отображается в хром-dev-инструментах:

POST http://192.168.1.2:3001/login 500 (Internal Server Error)

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

Можно ли настроить axios, чтобы не регистрировать ошибку в инструментах dev? Я не хочу, чтобы конечный пользователь это видел.

14 апр. 2018, в 12:07

Поделиться

Источник

4 ответа

Просто улучшение выше… Чтобы гарантировать, что ошибка исходит из вашего вызова API, вы можете указать, что на уловках axios.

axios.post(
    /* ... */
).then(
    response => {/* do something with the response */}
).catch(
    error => if(error.response){
    console.log(error.response.data)
    // from here you get only the response that is generated from your API 
    and hence you can differrentiate if the error is local or external
}
);

Waweru Mwaura
14 апр. 2018, в 20:59

Поделиться

Для этого используется обработчик .catch(). Он axios.post() когда обещание, возвращенное axios.post() отклоняется:

axios.post(
    /* ... */
).then(
    response => {/* do something with the response */}
).catch(
    error => {/* do something with the error */}
);

Но вы действительно должны справиться с этим делом на стороне сервера. Сервер не должен возвращать 500 ответов. Этот ответ указывает на необработанную ошибку. Если ваш сервер обрабатывает эту ошибку, он должен вернуть более подходящий код ошибки. 500 сообщений следует считать ошибкой и должны быть исправлены, а не пытаться скрыть их от пользователя.

trixn
14 апр. 2018, в 09:51

Поделиться

Для меня работал следующий код:

axios.post('${BASE_URL}/', data, config)
   .then(response => {
        if (response.data.success) {
            console.log(response.data.message);
            resolve(response.data.message)
        } else {

            reject(response.data.message)
        }
    }).catch(err => {

        let e = { ...err
    }

    console.log(e.response.data);
    reject(e.response.data)

   })

})

Everistus Olumese
25 янв. 2019, в 06:24

Поделиться

Вот пример для обработки этого случая:

axios.post('/formulas/create', {
    name: "",
    parts: ""
})
.then(response => { 
})
.catch(error => {
});

Chasing Unicorn
14 апр. 2018, в 11:13

Поделиться

Ещё вопросы

  • 0AngularJS: of-repeat, of-if & JSON
  • 0Как получить текст из элемента?
  • 1Скриптовый интерфейс C #
  • 1Проверка содержимого EditText, как только пользователь вводит данные
  • 0Создать список пользователей в C ++
  • 0Создается только первое динамически генерируемое поле выбора
  • 0Не могу установить Composer на Mac (Yosemite)
  • 0Fancybox не работает с определенным селектором
  • 1Проблема в разборе JSON String
  • 0если щелкнуть 3 из 5 изображений, перейдите по ссылке
  • 1На маркерных кластерах листовок не отображаются значки
  • 0Удалить вызывает ошибку памяти с виртуальным деструктором в базовом классе
  • 1Значения оси x амхарта меняются, не двигаясь / не сдвигаясь
  • 0Заполните выпадающий список из другой таблицы MySQL — php
  • 1Нестандартное использование уведомления об ожидании в параллельных программах Java
  • 0Страница прокручивается, как только прокрутка div достигает своего конца
  • 1Функция расстояния Возвращение неправильной вещи
  • 0вложенные контроллеры, родительский доступ и синтаксис controllerAs
  • 1Очень простой вопрос меню для Android
  • 0Внутреннее соединение MySQL без строк
  • 0динамические данные ng-repeat не отображаются, пока доступны теги
  • 0Изменить данные в запросе http post с текстовым полем ввода
  • 0База данных mysql drop, которая существует с тем же именем
  • 0Пул MySQL в nodejs
  • 0Сохраните дополнительные данные при создании новой роли с Yii Rights Module
  • 0Как использовать ng-repeat в сетке
  • 1Написание пользовательских LinearLayout для Android
  • 0Использование 2 разных скриптов на одном и том же флажке
  • 0pyqt5 tablewidgets для извлечения данных
  • 1KMeans против KMeansClustering в tenorflow.contrib
  • 0угловые данные начальной загрузки не отображаются должным образом
  • 0JQUERY иногда элемент не найден, если элемент указан
  • 0angularjs присваивает всем html-элементам определенного типа собственную область видимости
  • 0Право соединения не может получить доступ к строке из другой таблицы в PHP
  • 0C ++ Как работает повышение духа паразитами
  • 1Адаптер не будет работать на реальном устройстве
  • 0Когда элемент находится в окне браузера, постепенно исчезают по порядку
  • 1Вставка значений в базу данных SQL Server
  • 1Почему ClaimsPrincipal имеет метод AddIdentity, но не метод RemoveIdentity?
  • 0Разрешения для вложенных папок HTML
  • 0Angular — Как создать повторно используемую форму «создания записи» или ее часть, которая помещает запись в родительскую область видимости
  • 1Могу ли я создать макет, используя XML-файл и код в упражнении?
  • 1Telerik RadGrid дизайн коррупции
  • 1Сбой Motorola на Android при использовании конфигурации
  • 0Doxygen — неправильный порядок модулей в pdf
  • 0Проверка формы и пароля хэша в php
  • 0Вставка данных с использованием Phalcon и отношений
  • 0MariaDB * .myi файлы не отображаются в файловом менеджере
  • 1Zip-архив библиотеки Android

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Possible hdd error detected
  • Possible cause repository is under maintenance or down wrong sources list url как исправить
  • Port overflow error
  • Poslednaja nadegda нет карты как исправить
  • Port open error перевод