【问题标题】:Error: Column "undefined" does not exist on endpoint错误:端点上不存在列“未定义”
【发布时间】:2020-11-10 03:35:30
【问题描述】:

我正在使用 postgresql 运行 express js,并尝试访问我的一个端点来更新我的 products 表上的列之一。每次我点击“添加到购物车”时,它都会触发一个函数,然后应该将 in_Cart 的值更改为 true,但由于某种原因,在第一次点击时我得到了上面的错误,但在第二次点击时它真的有效吗?谁能给我解释或解决为什么?这是我的端点代码:

//Update inCart in product
app.put("/carts/:id/inCart", async (req, res) => {
  try {
    const { id } = req.params;
    const { in_cart } = req.body;

    const updateString = `in_cart = ${in_cart}`;

    const updateProduct = await pool.query("UPDATE products SET " +updateString+ " WHERE id = $1", [id]);

    res.json("Successfully Updated in_Cart");
  } catch (err) {
    console.log(err);
  }
})

这是我到达端点的 javascript 页面:

import React, { Component, useEffect, useState } from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams
} from "react-router-dom";
import "./ProductPageBody.scss";

const ProductPageBody = () => {
  const [products, setProducts] = useState([]);

  let { shirtName } = useParams();
  let shirts = products.filter(product => product.name === shirtName);

  const [in_cart, set_in_cart] = useState(shirts.in_cart);
  
  useEffect(() => {
    getProducts();
  }, []);

  const getProducts = async () => {
    try {
      const response = await fetch("http://localhost:5000/carts/");
      const jsonData = await response.json();

      setProducts(jsonData);
    } catch (err) {
      console.error(err.message);
    }
  };

  //Update in_cart Function
  const updateInCart = async (e, shirt) => {
    try {
      set_in_cart(true);
      const body = { in_cart };
      // ${shirts.id}
      const response = await fetch(`http://localhost:5000/carts/${shirt.id}/inCart`, {
        method: "PUT",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify(body)
      })
      console.log(response);

    } catch (err) 
    {
      console.error(err.message)  
    }
  } 
  return (
    <div
      className="container-fluid mt-5 m-auto p-0"
      style={{ paddingTop: "74px" }}
    >
      {shirts.map((shirt) => (
        <div className="row" key={shirt.id}>
          <div className="col-md-12 col-lg-4 ml-auto">
            <img
              src={shirt.image}
              alt={shirt.name}
              className="img-responsive w-100"
            />
          </div>

          <div className="col-md-12 col-lg-3 h-25 mt-5 mr-auto">
            <h1>{shirt.name}</h1>
            <div className="Pricing mt-3 mb-5">
              <h3 className="text-danger float-left mr-4">
                ${shirt.price}
              </h3>
              <select className="buttons form-control float-left mb-2">
                <option>Small</option>
                <option>Medium</option>
                <option>Large</option>
              </select>
              <button
                type="button"
                className="buttons btn btn-danger mt-2 h-auto w-100"
                onClick={e => updateInCart(e, shirt)}
              >
                ADD TO CART
              </button>
            </div>

            <p>{shirt.description}</p>
            <ul className="mt-2">
              <li>{"95% polyester, 5% elastane (fabric composition may vary by 1%)"}</li>
              <li>{"95% polyester, 5% elastane (fabric composition may vary by 1%)"}</li>
            </ul>
          </div>
        </div>
        ))}
    </div>
  );
};

export default ProductPageBody;

谢谢!

【问题讨论】:

    标签: javascript reactjs postgresql express


    【解决方案1】:

    也许您的 body 正在作为 undefined 传递到您的端点。
    造成这种情况的原因之一是您在updateInCart 内执行set_in_cart。并且set_in_cart 调用是异步的,因此您不会在调用set_in_cart 后立即获得in_carts 值。
    相反,您可能会获得未定义的或初始值或先前的值,并且在第二次单击时,您将获得在上次单击时设置的 in_cart 的值。
    为避免这种情况,您可以直接使用 in_cart 即 true 值,然后将其设置为状态。
    setStateasynchronous - Why is setState in reactjs Async instead of Sync?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-10
      • 2020-01-03
      • 2019-08-28
      • 1970-01-01
      • 2018-05-30
      • 2015-04-28
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多