我如何通过react向后端发送查询字符串

问题描述 投票:0回答:1
import React, { useEffect, useState } from "react";
import { Form, Row, Col, Button } from "react-bootstrap";
import { useParams, useNavigate } from "react-router-dom";

const FilterComponent = ({  categories, brands }) => {
    const { keyword} = useParams();

  const [category, setCategory] = useState(null);
  const [brand, setBrand] = useState(null);
  const [rating, setRating] = useState(null);
  const navigate = useNavigate(); 

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const param1 = params.get("category");
    const param2 = params.get("brand");
    const param3 = params.get("rating");
   

    // Only update state if the parameters are not null
    if (param1 !== null) {
      setCategory(param1);
    }
    if (param2 !== null) {
      setBrand(param2);
    }
    if (param3 !== null) {
      setRating(param3);
    }
    

    console.log(param1);
    console.log(param2);
    console.log(param3);
    console.log(category);
    console.log(brand);
    console.log(rating);
  }, [category, brand, rating, keyword, navigate ]);

  const handleCategoryChange = (event) => {
    const selectedCategory = event.target.value;
    setCategory(selectedCategory);
    console.log('category selected 1:', selectedCategory);
    if (selectedCategory){
        console.log('category selected 2:', selectedCategory);
        console.log('URL Parameters:', keyword);
        console.log(category)
        navigate(`/search/${keyword}/filter?category=${selectedCategory}&brand=${brand}&rating=${rating}`);  
    }
};

  const handleBrandChange = (event) => {
    const selectedBrand = event.target.value;
    setBrand(selectedBrand);
    if (selectedBrand){
        navigate(`/search/${keyword}/filter?category=${category}&brand=${selectedBrand}&rating=${rating}`);  
    }
  };

  const handleRatingChange = (event) => {
    const selectedRating = Number(event.target.value);
    setRating(selectedRating);
    if (selectedRating){
        navigate(`/search/${keyword}/filter?category=${category}&brand=${brand}&rating=${selectedRating}`);  
    }
  };

  const handleClearFilters = () => {
    setCategory("");
    setBrand("");
    setRating("");
  };

  return (
    <div>
      <h2>Filter By</h2>
      <Form>
        <Row className="d-flex flex-column ">
          <Col>
            <Button variant="secondary" onClick={handleClearFilters}>
              Clear Filters
            </Button>
          </Col>
          <Col>
            <Form.Group controlId="category">
              <Form.Label>Category</Form.Label>
              <Form.Control
                as="select"
                value={category}
                onChange={handleCategoryChange}
              >
                <option value="">All Categories</option>
                {categories.map((category, index) => (
                  <option key={index} value={category}>
                    {category}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>
          </Col>
          <Col>
            <Form.Group controlId="brand">
              <Form.Label>Brand</Form.Label>
              <Form.Control
                as="select"
                value={brand}
                onChange={handleBrandChange}
              >
                <option value="">All Brands</option>
                {brands.map((brand, index) => (
                  <option key={index} value={brand}>
                    {brand}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>
          </Col>
          <Col>
            <Form.Group controlId="rating">
              <Form.Label>Rating</Form.Label>
              <Form.Control
                as="select"
                value={rating}
                onChange={handleRatingChange}
              >
                <option value="">All Ratings</option>
                {[...Array(5)].map((_, index) => (
                  <option key={index + 1} value={index + 1}>
                    {index + 1} Stars
                  </option>
                ))}
              </Form.Control>
            </Form.Group>
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default FilterComponent;


查询

getProducts: builder.query({
      query: ({ keyword, pageNumber, category, brand, rating}) => ({
        url: PRODUCTS_URL,
        params: {
          keyword,
          pageNumber,
          category, 
          brand,
          rating,
        },
      }),
      providesTags: ["Products"],
      keepUnusedDataFor: 5,
    }),

前端路由

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<App />}>
      <Route index={true} path="/" element={<HomeScreen />} />
      <Route path="/search/:keyword" element={<HomeScreen />} />
      <Route path="/search/:keyword/filter" element={<HomeScreen />} />
)
)

在后端我尝试控制台 req.query 它显示未定义未定义未定义

// @desc    Fetch all products
// @route   GET /api/products
// @access  Public
const getProducts = asyncHandler(async (req, res) => {
 
 
  const { category, brand, rating } = req.query; // Get the filter parameters from the query string
  console.log(category, brand, rating);

我变得未定义未定义未定义为什么?

假设如果选择 “电子产品”作为类别 “苹果”作为品牌 “4 星”评级

我在后台期待

electronics apple 4 star
但我实际上得到了什么
undefined undefined undefined

并且“关键字”已成功进入后端

我不明白为什么它没有进入后端控制器

有没有人可以解答我的疑惑???

reactjs node.js express redux query-string
1个回答
0
投票

问题源于像

category
brand
rating
这样的参数,尽管是从前端发送的,但在后端却是
undefined
。解决方法:

  1. 检查前端路由以确保参数正确包含在 URL 中。
  2. 确认路由配置接受这些参数。
  3. 确保参数的 URL 编码正确。
  4. 使用
    req.query
    验证后端代码是否正确解析查询参数。

通过检查网络请求、确认前端 URL 构造并检查后端解析来进行调试。修复这些点应该可以解决后端

undefined
参数的问题。

© www.soinside.com 2019 - 2024. All rights reserved.