【发布时间】:2021-08-06 10:35:27
【问题描述】:
例如,如果有名称为“playstation (white)”的产品,如果我搜索“playstation”或“white”甚至是“(白色)”,结果显示。但如果我搜索“playstation(白色)”,结果为空。
我认为这个错误是由于正则表达式,因为当我尝试输入例如:'playstation ('
出现此错误Regular expression is invalid: missing)。但我不知道如何解决。
当我尝试搜索“playstation /(white/)”时,
假设有 3 种产品:playstation(白色)、playstation(黑色)、xbox
它显示playstation(白色)和playstation(黑色)
这是我的代码
后端productController.js
const getProducts = asyncHandler(async (req, res) => {
const pageSize = 10
const page = Number(req.query.pageNumber) || 1
const keyword = req.query.keyword
? {
name: {
$regex: req.query.keyword,
$options: 'i',
},
}
: {}
const count = await Product.countDocuments({ ...keyword })
const products = await Product.find({ ...keyword })
.limit(pageSize)
.skip(pageSize * (page - 1))
res.json({ products, page, pages: Math.ceil(count / pageSize) })
})
前端 searchBox.js
import React, { useState } from "react";
import { Form } from "react-bootstrap";
const SearchBox = ({ history }) => {
const [keyword, setKeyword] = useState("");
const submitHandler = (e) => {
e.preventDefault();
if (keyword.trim()) {
history.push(`/search/${keyword}`);
} else {
history.push("/");
}
};
return (
<Form onSubmit={submitHandler}>
<Form.Control
type="text"
name="q"
onChange={(e) => setKeyword(e.target.value)}
placeholder="Search...."
className="search-box"
/* className="mr-sm-2 ml-sm-5" */
></Form.Control>
{/* <Button type="submit" variant="outline-success" className="p-2">
<div style={{ color: "white" }}>Search</div>
</Button> */}
</Form>
);
};
export default SearchBox;
【问题讨论】:
标签: javascript node.js reactjs regex