仅Axios Vue应用发布请求网络错误

时间:2020-08-12 12:47:41

标签: node.js express http axios postman

使用以下Stack Express,Vue,SQL,Axios

  1. GET请求在Axios的邮递员中也能正常工作
  2. POST请求在两个随附的屏幕截图中创建了错误
  3. 为确保后端正常运行,我尝试了直接从
  4. 发送数据
<form action="url" method="POST"> 

一切正常,数据存储在数据库中

我尝试了几种解决方法,例如在邮递员中禁用SSL设置,并使用代理设置进行播放。还在后端启用了CORS,并尝试了一些“允许内容和标头”操作。什么都没用

无法确定POST请求中的问题。请帮助

-从Axios的浏览器中请求错误----
Axios Browser Error

-postman执行POST请求时发生错误--- Postman Error

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

我意识到,您正在向后端发送一个PUT请求,但是您的API控制器接收到POST请求。因此,他们不必一定是同一类型的请求吗?