首页 > 解决方案 > Axios Vue 应用程序仅发布请求网络错误

问题描述

使用以下堆栈 Express、Vue、SQL、Axios

  1. GET 请求在邮递员以及来自 Axios 的工作正常
  2. POST 请求在两个附加的屏幕截图中创建了错误
  3. 为了确保后端工作正常,我尝试直接从
<form action="url" method="POST"> 

它工作正常,数据存储在数据库中

我尝试了一些解决方法,例如在邮递员中禁用 SSL 设置并使用代理设置播放也在后端启用了 CORS 并尝试了一些允许内容和标题的东西。没有任何效果

无法找出 POST 请求中的问题。请帮忙

--Axios浏览器中的Request Error ----
Axios Browser Error

-postman 执行 POST 请求时出错--- Postman 错误

---后端Index.js文件---

// 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 路由文件---

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;

---产品文件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");
  });
};

--前端axios请求--

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));

标签: node.jsexpresshttpaxiospostman

解决方案


我得到了答案,我app.use(bodyParser.json)index.js中缺少一个中间件,因此没有任何值进入数据库,因此出现了网络错误。


推荐阅读