Newboy11
Newboy11

Reputation: 3134

Socket hang up when using axios

I'm having an error "Error: socket hang up" and I don't know what causes this but it saves the data in database.

here's my code:

dataschema.js

const mongoose = require("mongoose");

const DataSchema = new mongoose.Schema({
  data1: {
    type: String
  },
  data2: {
    type: String
  },
  data3: {
    type: String
  },
  data4: {
    type: String
  },
});

const DataModel = mongoose.model("TEST123", DataSchema);

module.exports = DataModel;

routes.js

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const DataModel = require('./models/dataschema');

var bodyParser = require('body-parser');
app.use(bodyParser.json());

mongoose.connect(
    "mongodb://localhost:27017/stocksmonitor?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false",
    { useNewUrlParser: true }
);

app.post('/insert', (req, res) => {

    const stock = new DataModel({
        data1: req.body[0],
        data2: req.body[1],
        data3: req.body[2],
        data4: req.body[3],
    })
    
    stock.save();
    
})

app.listen(3001, () => {
    console.log("You are connected");
})

savedata.js

const axios = require('axios');

SaveInfo = () => {

  const testdata = ["a", "b", "c", "d"]

  axios({
      method: 'post',
      url: 'http://localhost:3001/insert',
      data: testdata
  })
  .then(function (response) {
      console.log(response);
  })
  .catch(function (error) {
      console.log(error);
  });
}
SaveInfo(); 

Upvotes: 4

Views: 6464

Answers (1)

Eren Yatkin
Eren Yatkin

Reputation: 326

I inspected the code and found that you did not return response for your controller. In the code below after the save add res.send() or res.json(). So express can return a proper response. Otherwise request will timed out, because it did not resolve and Express will cut the connection. Therefore axios is throwing Error: Socket hang up unexpectedly.

app.post('/insert', (req, res) => {

    const stock = new DataModel({
        data1: req.body[0],
        data2: req.body[1],
        data3: req.body[2],
        data4: req.body[3],
    })
    
    stock.save();
})

Upvotes: 1

Related Questions