node.js - Axios Vue 应用程序仅发布请求网络错误
问题描述
使用以下堆栈 Express、Vue、SQL、Axios
- GET 请求在邮递员以及来自 Axios 的工作正常
- POST 请求在两个附加的屏幕截图中创建了错误
- 为了确保后端工作正常,我尝试直接从
<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));
解决方案
我得到了答案,我app.use(bodyParser.json)
在index.js中缺少一个中间件,因此没有任何值进入数据库,因此出现了网络错误。
推荐阅读
- javascript - 使用jquery为多个元素制作交错淡入淡出循环
- nuxt.js - 为什么我必须在我的 Nuxt.js 插件中显式调用 jquery 和 bootstrap,当它在供应商中全局加载时?
- c# - 如何从 Windows.Form 调用 UserControl 的方法
- python-3.x - Python 3.x - 如何使用请求补丁更新 Google Drive 上的 CSV 文件
- javascript - ReactJS 教程井字游戏
- python - 将项目附加到另一个文件中的列表 - Python
- shopware - 如何显示博客文章中的所有图像
- android - RXAndroid 编写嵌套订阅的更好方法
- elasticsearch - 如何更新映射
- javascript - 单击按钮为文本添加下划线 JavaScript