Issue with Axios in Vue app: Only receiving network errors for Post requests

Using the Following Stack Express,Vue,SQL,Axios

  1. Successful GET request in postman and Axios
  2. Error encountered with POST request, see attached screenshots
  3. To test backend functionality, data was sent directly from a form
<form action="url" method="POST"> 

Data successfully stored in database using the form

Attempts to troubleshoot included disabling SSL in Postman, adjusting proxy settings, enabling CORS on the backend, and modifying content and header settings. However, none of these solutions resolved the issue.

Inability to identify the root cause of the error with the POST Request. Seeking assistance for resolution

--Encountered Error Message from Axios in the browser --
Axios Browser Error

--Error message received from Postman during POST Request--
Postman Error

---Index.js file for Backend---

// const express = require("express");
"use strict";

import express from "express";
const app = express();
import cors from "cors";

//listening on this port
app.listen(3000);

app.use(cors()); // to get Data from Other Domains

app.get("/", function (req, res) {
  res.send("Application Started");
  console.log("Application Started");
});

//Routes
app.use("/product", require("./routes/product"));

---product.js routes files---

import express from "express";
const router = express.Router();
import bodyParser from "body-parser";

//Middleware
router.use(bodyParser.urlencoded({ extended: true })); // To Parse the body data

//Importing Main Controller
import conProduct from "../controllers/ConProduct";

//Defining functions as per Routes
router.post("/add", conProduct.add); //Showing all the products
router.get("/get", conProduct.get); //Showing all the products

//Exporting Router
module.exports = router;

---Controller for Product file ConProducts.js ---

import sqlConfig from "../database/dbConfig";
let sql = sqlConfig.mysql_pool;

exports.add = (req, res) => {
  console.log(req.body);
  const { name, shortDescription, price, discount } = req.body;

  let addQuery =
    "INSERT INTO products(name,short_description,price,discount) VALUES('" +
    name +
    "','" +
    shortDescription +
    "','" +
    price +
    "','" +
    discount +
    "');";

  sql.query(addQuery, (err, result) => {
    if (err) throw err;
    console.log(result);
    res.send("product uploaded");
  });
};

--Frontend axios Request --

let formData = {
        name: this.name,
        shortDescription: this.shortDescription,
        price: this.price,
        discount: this.discount,
      };
      console.log(formData);
      axios
        .post("/product/add", formData)
        .then((res) => console.log(res))
        .catch((error) => console.log(error));

Answer №1

After some troubleshooting, I found the solution to my issue. It turns out that I had forgotten to include a middleware app.use(bodyParser.json) in my index.js file. This caused a problem where no values were being sent to the database, resulting in a network error.

Answer №2

It occurred to me that you are attempting to send a PUT request to the backend, but your API controller is set up to receive only POST requests. Shouldn't they both be configured to handle the same type of request?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging string interpolation in Typescript with a string sourced from a file

After diving into Typescript, I came across some intriguing information on template strings. One question that popped into my mind is whether these template strings can be utilized when reading a string from a file, just like this: let xmlPayloadTemplate ...

What is the method for configuring my bot to forward all logs to a specific channel?

const logsChannel = message.guild.channels.cache.find(channel => channel.name === 'logs'); I am looking to set up my bot to send log messages for various events, like member join/leave or message deletion, specifically in a channel named &apo ...

Changes made by updateOnDuplicate are ineffective

Hello, I am looking to insert data using the bulkCreate method. Here is an example of the data: [ { "typeId": 5, "devEui": "0094E796CBFCFEF9", "application_name": "Pressure No.10", "createdAt": "2020-02-05T08:07:17.000Z ...

What is the process of extracting a utility function from a helper file on a node.js server?

I'm facing a challenge with my node/express server where I need to access a function from a helper file in my app.js. The function in the helper file looks like this: CC.CURRENT.unpack = function(value) { var valuesArray = value.split("~"); ...

I am experiencing difficulties with Capistrano, as the remote shell, Node.js, and Yarn

Experiencing an issue: Yarn requires Node.js 4.0 or higher to be installed Upon SSH into the remote server, I have: passwords@meet:/srv/passwords$ yarn -v 1.22.5 passwords@meet:/srv/passwords$ node -v v16.9.1 passwords@meet:/srv/passwords$ Node is instal ...

Leveraging Promises in Mongoose as Arguments for other Functions

I am interested in mastering the concept of promises, particularly for querying data and using that information to further query other data. Here is an example of a Schema I have: var serviceSchema = new Schema({ name: String, }); Within this Schema, th ...

Challenge in resolving a promise returned by the find() function in mongodb/monk

I've encountered an issue where the simple mongodb/monk find() method isn't working for me. I am aware that find() returns a promise and none of the three ways to resolve it seem to be successful. Can someone point out what mistake I might be mak ...

Bundling extraneous server code in client rollup

Can someone help me understand why the following code is being included at the top of my browser bundle by Rollup? It seems like these references are not used anywhere from my entry point. Could it be default includes from node builtins? import require$$0$ ...

While running a Conda command through a Node.js script with the use of PM2, I encountered an error stating "/bin/sh: 1: conda: not

Overview In the production environment, I am utilizing pm2 to run a nodejs server. The server executes a javascript file that triggers a python script using the conda run method. Unfortunately, an error occurs with the message: /bin/sh: 1: conda: not foun ...

"Oops! Looks like npm command is missing in the system. Please install

After installing express globally, I keep getting this message. I have tried numerous solutions concerning the /.bash_profile file and exporting the correct PATH, but nothing seems to work. One solution I attempted from worked in the terminal. However, ...

Heroku deployment unable to refresh node modules after git push

Can someone assist me with a problem I'm encountering while trying to deploy my project on Heroku? The issue revolves around my utilization of "react-animations" and the customization I've applied to a particular animation within the library. Ess ...

Assistance needed with WebSocket and Node.js: Unable to connect to wss://domain:8080 - Issue is not specific to any browser

Greetings, this is my initial inquiry on stack overflow so I'll give it my best shot. Despite going through numerous related questions, I haven't found the solution to my issue. I recently delved into Node.js because I required websockets for ce ...

The elusive Mongoose slipped through the MongoDB/Atlas, leaving behind nothing but an Express 404

I'm currently diving into MongoDB and facing an ongoing issue that's been puzzling me for quite some time now. Despite following various tutorials, I keep encountering a frustrating 404 error and I'm at a loss as to what might be causing it. ...

When I navigate away from the page on Node, the cookie is promptly deleted

After accessing my node app, I am creating a cookie using the following code: app = require("express")(); httpServer = require("https").createServer(options,app); cookie = require("cookie"); app.get('/site', functio ...

outputting console.log as a debug message with HEX code written to the buffer

I am currently experimenting with zwack (https://github.com/paixaop/zwack) and attempting to monitor the HEX values being written to the buffer in order to replicate a FTMS machine/server. Here is the code snippet: onReadRequest(offset, callback) { de ...

NPM seems to be neglecting the presence of globally installed packages

I seem to be encountering an issue with locally installing packages while globally installed ones are accessible. It appears that there is an error with the include path, but I am uncertain about the root cause. System : Mac OS X Node : 8.3.1 NPM ...

The bot has decided to send the generic response instead of executing a custom action

I'm experimenting with the concept of developing a bot to interact with our team's chat tool and ticketing system. I currently have a basic bot set up to retrieve the status of a task record in the system and provide a response. However, I encoun ...

Upon running NPM start, an inexplicable error arises when attempting to execute "gulp clean && gulp frontend && gulp dev" in the package.json file

After diligently following the steps outlined in this tutorial, I hit a roadblock at the frontend tasks stage. Upon running NPM with npm start, I encountered the following error: https://i.stack.imgur.com/bvS1e.jpg I identified the issue to be either the ...

The retrieval process takes place only one time or when I access the developer tools

I am currently developing a website where I need to retrieve reports from mongoDB and display markers on a map based on the locations of these reports. However, I am facing an issue where this functionality only works once when I initially open the website ...

What is the best way to send an axios request in a Vue component to a route created by an Adonis controller?

My WidgetController.js file is responsible for handling CRUD operations on the database. Within this controller, there is a method/generator called * create (request, response) which returns widget attributes in a response and also inserts a new row into t ...