Express对接MongoDB Atlas实现模糊搜索、React展示及URL验证问题
1 后端路由代码实现
后端基于Express框架,需要新增搜索接口路由和对应的控制器逻辑:
// routes/posts.js 路由文件新增代码 import express from 'express'; import { getPosts, searchPosts } from '../controllers/posts.js'; const router = express.Router(); router.get('/', getPosts); // 新增搜索接口 router.get('/search', searchPosts); export default router;
// controllers/posts.js 控制器文件新增代码 import PostMessage from '../models/PostMessage.js'; export const searchPosts = async (req, res) => { const { keyword } = req.query; try { // 调用mongoose模糊搜索插件的fuzzySearch方法 const searchResults = await PostMessage.fuzzySearch(keyword); res.status(200).json(searchResults); } catch (error) { res.status(404).json({ message: error.message }); } };
2 React端搜索结果展示实现
无需修改原有Posts组件,只需要新增搜索请求逻辑、绑定搜索组件事件即可:
调整App组件代码
// App.js 调整部分逻辑 const App = () => { const [currentId, setCurrentId] = useState(0); // 新增搜索关键词状态 const [searchKeyword, setSearchKeyword] = useState(''); const dispatch = useDispatch(); const classes = useStyles(); useEffect(() => { dispatch(getPosts()); }, [currentId, dispatch]); // 搜索触发逻辑 const handleSearch = () => { if (searchKeyword.trim()) { dispatch(searchPosts(searchKeyword)); } else { // 关键词为空时返回全部帖子 dispatch(getPosts()); } }; return ( <Container maxWidth="lg" > <AppBar className={classes.appBar} position="static" color="inherit"> <Typography className={classes.heading} variant="h2" align="center">Search Bar</Typography> {/* 绑定搜索组件事件 */} <SearchBar value={searchKeyword} onChange={(newValue) => setSearchKeyword(newValue)} onRequestSearch={handleSearch} onCancelSearch={() => { setSearchKeyword(''); dispatch(getPosts()); }} /> </AppBar> {/* 其余原有代码保持不变 */} </Container> ); };
新增Redux相关逻辑
// actions/posts.js 新增搜索action export const searchPosts = (keyword) => async (dispatch) => { try { const { data } = await api.searchPosts(keyword); dispatch({ type: 'FETCH_ALL', payload: data }); } catch (error) { console.log(error.message); } };
// api/index.js 新增搜索请求方法 export const searchPosts = (keyword) => axios.get(`/posts/search?keyword=${keyword}`);
搜索返回的结果会直接替换Redux中存储的帖子列表,原有Posts组件会自动渲染搜索结果。
3 URL校验功能实现
建议前后端双重校验,避免非法数据入库:
后端Schema校验
修改Post的Schema配置,给link字段加正则匹配规则:
const postSchema = mongoose.Schema({ // 其余字段保持不变 link: { type: String, // 匹配http/https开头的合法URL match: [/^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/, '请输入合法的URL地址'] }, })
前端表单校验
在Form组件提交逻辑中加入URL校验:
// Form组件提交逻辑新增校验 const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/; const handleSubmit = (e) => { e.preventDefault(); if (postData.link && !urlRegex.test(postData.link)) { alert('请输入合法的URL地址'); return; } // 原有提交逻辑保持不变 }
内容的提问来源于stack exchange,提问作者Yosi Oren
相关产品推荐
相关产品推荐

