Derteck
Derteck

Reputation: 101

Axios post is giving me an error: Internal server Error

I am doing a post request with Axios and gives me this error:

xhr.js:178 POST http://localhost:3000/dependentes 500 (Internal Server Error)

I have seen people asking about this but none of their solutions work for me! I don't know if is something wrong in this component or I have something wrong with the server side.

import React, { Component } from "react";
import axios from "axios";

class LogIn extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChangeEmail = this.handleChangeEmail.bind(this);
    this.handleChangePass = this.handleChangePass.bind(this);
  }

  handleChangeEmail = e => {
    this.setState({ email: e.target.value });
    //console.log(e.target.value);
  };

  handleChangePass = e => {
    this.setState({ password: e.target.value });
    //console.log(e.target.value);
  };

  handleSubmit = e => {
    /*this.props.history.push('/');
        console.log(this.props);*/

    event.preventDefault();

    let data = JSON.stringify({
      email: this.state.email,
      password: this.state.password
    });
    let url = "http://localhost:3000/dependentes";
    const response = axios.post(url, data, {
      headers: { "Content-Type": "application/json" }
    });
  };

  render() {
    return (
      <div className="container">
        <form onSubmit={this.handleSubmit} className="white">
          <h5 className="grey-text text-darken-3">Log In</h5>
          <div className="input-field">
            <label htmlFor="email">Email</label>
            <input
              type="email"
              id="email"
              onChange={this.handleChangeEmail}
              value={this.state.email}
            />
          </div>
          <div className="input-field">
            <label htmlFor="password">Password</label>
            <input
              type="password"
              id="password"
              onChange={this.handleChangePass}
            />
          </div>
          <div className="input-field">
            <button className="btn orange lighten-1 z-depth-0">Log In</button>
          </div>
        </form>
      </div>
    );
  }
}

export default LogIn;

Upvotes: 0

Views: 2274

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12552

According to your node.js code you are NOT using body-parser that's why getting email from req.body will throw you an error because req.body is undefined.

Also, If you don't return the request like res.send or res.json it will always time out from front end as the request is not closed.

So, to edit your code

//installed express, mysql, cors

const config = require('./database/config');
const express = require('express');
const cors = require('cors');
const port = 4000;
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser'); // <=== this line
app.use(cors());
app.use(bodyParser.json()); //<=== This line

const SELECT_ALL_ADDICTS_QUERY = 'SELECT * FROM viciados';

const connection = mysql.createConnection(config.mysql);

connection.connect(err => {
  if (err) {
    return err;
  }
});

app.get('/', (req, res) => {
  res.send('Homepage. Go to /dependentes para ver os dependentes no sistema');
  res.end();
});

app.get('/dependentes', (req, res) => {
  connection.query(SELECT_ALL_ADDICTS_QUERY, (err, results) => {
    if (err) {
      res.send(err);
    } else {
      res.json({
        data: results
      });
    }
  });
});

app.post('/dependentes', (req, res) => {
  console.log(req.body.email);
  res.json({ email: req.body.email }); ///<== and this line
});

app.listen(port, err => {
  return err
    ? console.log(`error founded: ${err}`)
    : console.log(`server runnning on port: ${port}`);
});


Upvotes: 1

Related Questions