利用node.js将前端的搜索栏与数据库连接
时间: 2024-05-06 22:17:34 浏览: 7
要实现前端搜索栏与数据库的连接,你需要使用Node.js作为后端服务器,以及一个数据库(例如MySQL)来存储数据。
以下是大致的步骤:
1. 安装Node.js和MySQL,并建立一个数据库和表来存储搜索数据。
2. 在Node.js中,使用npm安装Express框架,用于搭建后端服务器。
3. 创建一个API路由,用于处理前端搜索栏提交的数据,并查询数据库中符合条件的数据返回给前端。
4. 在前端页面中,使用Ajax或Fetch等技术,将搜索栏提交的数据发送到后端API路由。
5. 接收到后端API路由的返回数据后,将数据展示在前端页面中。
以下是一个简单的示例代码:
后端代码(server.js):
```javascript
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// 连接数据库
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
connection.connect();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 处理前端搜索栏提交的数据,并返回符合条件的数据
app.post('/search', (req, res) => {
const keyword = req.body.keyword;
const query = `SELECT * FROM mytable WHERE name LIKE '%${keyword}%'`;
connection.query(query, (error, results, fields) => {
if (error) throw error;
res.json(results);
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
```
前端代码(index.html):
```html
<!DOCTYPE html>
<html>
<head>
<title>Search Example</title>
</head>
<body>
<input type="text" id="keyword">
<button id="searchBtn">Search</button>
<ul id="results"></ul>
<script>
const searchBtn = document.getElementById('searchBtn');
const keyword = document.getElementById('keyword');
const results = document.getElementById('results');
searchBtn.addEventListener('click', () => {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/search');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
let html = '';
data.forEach(result => {
html += `<li>${result.name}</li>`;
});
results.innerHTML = html;
} else {
console.log('Error');
}
};
xhr.send(JSON.stringify({ keyword: keyword.value }));
});
</script>
</body>
</html>
```
这是一个简单的示例,你可以根据你的需求进行修改和扩展。