连接前端和后端(CRUD-与fileUpload)

时间:2019-04-22 08:16:22

标签: node.js express

请帮助我...我制作了一些程序(CRUD)。

我正在使用rest API。因此,我创建了一个后端和前端。 但是我有一个问题。当我用邮递员测试后端时,一切都很好(可以将数据保存在PostgreSQL数据库中)。

当我尝试使用前端发送数据时,无法发送数据。特别是在通过文件上传发送数据时遇到问题...请帮忙

  

前端代码

<form id="add-form" class="form-horizontal">
    <div class="form-group">
      <label for="inputProduct" class="col-sm-2 control-label"> Product Name </label>
      <div class="col-md-10">
        <input type="text" class="form-control" id="inputProduct" name="productName" placeholder="Product Name">
      </div>
    </div>

    <div class="form-group">
      <label for="inputProductDesc" class="col-sm-2 control-label"> Product Description </label>
      <div class="col-md-10">
        <textarea class="form-control" id="inputProductDesc" name="productDesc" placeholder="Product Description"></textarea>
      </div>
    </div>

    <div class="form-group">
      <label for="booleanProduct" class="col-sm-2 control-label"> Product Enable </label>
      <div class="col-md-10">
        <select class="form-control" id="booleanProduct" name="productEnable">
          <option>Chosee the boolean...</option>
          <option>True</option>
          <option>False</option>
        </select>
      </div>
    </div>

    <div class="form-group">
      <label for="userFile" class="col-sm-2 control-label">Image</label>
      <div class="col-md-10">
        <input type="file" class="form-control" id="userFile" name="doc">
      </div>
    </div>

    <div class="form-group">
      <label for="booleanImage" class="col-sm-2 control-label"> Image Enable </label>
      <div class="col-md-10">
        <select class="form-control" id="booleanImage" name="imageEnable">
          <option>Chosee the boolean...</option>
          <option>True</option>
          <option>False</option>
        </select>
      </div>
    </div>

    <div class="form-group">
      <label for="inputCategory" class="col-sm-2 control-label">Category Product</label>
      <div class="col-md-10">
        <input type="text" class="form-control" id="inputCategory" name="categoryName" value="">
      </div>
    </div>

    <div class="form-group">
      <label for="booleanCategory" class="col-sm-2 control-label"> Category Enable </label>
      <div class="col-md-10">
        <select class="form-control" id="booleanCategory" name="categoryEnable">
          <option>Chosee the boolean...</option>
          <option>True</option>
          <option>False</option>
        </select>
      </div>
    </div>

    <br>
    <div class="form-group">
      <div class="col-md-3" align="center">
        <button type="submit" class="btn btn-primary">Add Product</button>
      </div>
    </div>

  </form>
<script>
$(document).ready(function(){
  })

  $('#add-form').submit(function(e){
    e.preventDefault();
    saveData();
  });
function saveData(){

let productName = $('#inputProduct').val()
let productDesc = $('#inputProductDesc').val()
let productEnable = $('#booleanProduct').val()
let doc = $('#userFile').val()
let imageEnable = $('#booleanImage').val()
let categoryName = $('#inputCategory').val()
let categoryEnable = $('#booleanCategory').val()

$.ajax({
  url: 'http://localhost:3000/api/product/',
  method: "POST",
  data: {
    productName: productName,
    productDesc: productDesc,
    productEnable: productEnable,
    doc: fileImage,
    imageEnable: imageEnable,
    categoryName: categoryName,
    categoryEnable: categoryEnable
  }
}).done(() => {
  getData();
})

}

  

后端代码

    // ADD product
  router.post('/',(req, res) => {
    let data = {
      productName: req.body.productName,
      productDesc: req.body.productDesc,
      productEnable: req.body.productEnable,
      categoryName: req.body.categoryName,
      categoryEnable: req.body.categoryEnable,
      imageEnable : req.body.imageEnable
    }

    // Upload File
    let fileImage = req.files.doc;
    let imageName = `${data.productName}` + '-' + fileImage.name;

    console.log("File Image :", fileImage);
    console.log("Image Name :", imageName);

    fileImage.mv(path.join(__dirname, '../public/upload/') + imageName, function(err) {
      if(err){
        console.log(err);
      }else{
        console.log("Uploaded");
      }
    });

    let sql =
    `INSERT INTO product (name, description, enable) VALUES ('${data.productName}', '${data.productDesc}', '${data.productEnable}') RETURNING *`;
    pool.query(sql, (err, insertProduct) => {
      let sql2 = `INSERT INTO category (category_name, category_enable) VALUES ('${data.categoryName}', '${data.categoryEnable}') RETURNING *`;
      pool.query(sql2, (err, insertCategory) => {
        let sql3 = `INSERT INTO category_product (id_category, id_product) VALUES (${insertCategory.rows[0].category_id}, ${insertProduct.rows[0].id})`;
        pool.query(sql3, (err) => {
          let sql4 = `INSERT INTO image (image_name, image_file, image_enable) VALUES ('${imageName}', '${fileImage.name}', '${data.imageEnable}') RETURNING *`;
          pool.query(sql4, (err, insertImage) => {
            let sql5 = `INSERT INTO product_image (product_id, image_id) VALUES (${insertProduct.rows[0].id}, ${insertImage.rows[0].id})`;
            pool.query(sql5).then(() => {
                // console.log("data :", data.rows[0]);
                res.json({
                  success : true,
                  message : "data has been added",
                  data :{
                    productName : insertProduct.rows[0].name,
                    descriptionProduct : insertProduct.rows[0].description,
                    productCategory : insertCategory.rows[0].category_name,
                    productImage : insertImage.rows[0].image_name
                  }
                })
              }).catch(err => {
                res.json({
                  success: false,
                  message: "adding data has been failed",
                })
              })
          })
        })
      })
    })
  })

0 个答案:

没有答案
相关问题