简体   繁体   English

错误:端点上不存在列“未定义”

[英]Error: Column “undefined” does not exist on endpoint

I am running express js with postgresql and trying to hit one of my endpoints to update one of my columns on my products table.我正在使用 postgresql 运行 express js,并尝试访问我的一个端点来更新我的产品表中的一个列。 Everytime I click "ADD TO CART" it triggers a function which should then change the value of in_Cart to true, but for some reason on the first click i get the error above, but then on the second click it actually works?每次我点击“添加到购物车”时,它都会触发一个 function,然后应该将 in_Cart 的值更改为 true,但由于某种原因,在第一次点击时我得到了上面的错误,但在第二次点击时它真的有效吗? Could anyone give me an explanation or soloution to why?谁能给我解释或解决为什么? Here is my endpoint code:这是我的端点代码:

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

and here is my javascript page that hits the endpoint:这是我到达端点的 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;

Thank You!谢谢你!

Maybe your body is getting passed as undefined to your endpoint.也许您的body正在以undefined的方式传递到您的端点。
One of the reasons for this is you are doing set_in_cart inside updateInCart .原因之一是您正在set_in_cart内进行updateInCart and set_in_cart call is async so you will not get in_cart s value immediately after the call to set_in_cart .并且set_in_cart调用是异步的,因此您不会在调用set_in_cart后立即获得in_cart的值。
Instead, you might get undefined or initial value or previous value, and on the second click, you will get the value of in_cart which is set on the previous click.相反,您可能会获得未定义的或初始值或先前的值,并且在第二次单击时,您将获得在上次单击时设置的in_cart的值。
To avoid this you can directly use in_cart that is true value and then set it into the state.为避免这种情况,您可以直接使用为true值的 in_cart,然后将其设置到 state 中。
setState is asynchronous - Why is setState in reactjs Async instead of Sync? setStateasynchronous的 - 为什么 reactjs 中的 setState 是异步而不是同步?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM