实现通过商品名字查找商品的前后端代码
前端代码:
// HTML
<input type="text" id="searchInput">
<button onclick="search()">搜索</button>
// JavaScript
function search() {
const searchInput = document.getElementById('searchInput').value;
fetch(`/api/products?name=${searchInput}`)
.then(response => response.json())
.then(data => {
// 处理返回的数据
})
.catch(error => console.error(error));
}
后端代码:
const express = require('express');
const app = express();
const products = [
{ id: 1, name: '手机', price: 1000 },
{ id: 2, name: '电视', price: 2000 },
{ id: 3, name: '电脑', price: 3000 },
];
app.get('/api/products', (req, res) => {
const name = req.query.name;
if (!name) {
return res.status(400).send('请提供商品名字');
}
const result = products.filter(product => product.name.includes(name));
res.send(result);
});
app.listen(3000, () => console.log('服务器已启动,端口号:3000'));
此代码假定你已经安装并正确配置了 Express。当用户在前端输入商品名字并点击搜索时,前端会发送一个 GET 请求到 /api/products?name={商品名字}。后端会根据请求中的查询参数 name,从 products 数组中筛选出符合条件的商品,并将结果返回给前端
原文地址: https://www.cveoy.top/t/topic/d3Xo 著作权归作者所有。请勿转载和采集!