nodejs 接口为httplocalhost3000apiblogsaddexportsaddBlogs = req res = const info = reqbody; const sqlStr = select from blogs_info where title = ; dbquerysqlStr infotitle err results = i
将以上两个文件对接的步骤如下:
- 在Node.js中创建一个Express应用,并在应用中引入以上两个文件。
- 在Express应用中设置路由,使得当访问"http://localhost:3000/api/blogs/add"时,调用
addBlogs函数。 - 在前端HTML文件中,将form表单的action属性设置为"http://localhost:3000/api/blogs/add",使得提交表单时会发送POST请求到该接口。
- 在前端HTML文件中,给保存按钮添加点击事件监听器,并在事件处理函数中调用表单的submit()方法,实现提交表单的功能。
完整的代码如下所示:
Node.js文件(app.js):
const express = require('express');
const app = express();
// 引入数据库操作模块和addBlogs函数
const db = require('./db');
const { addBlogs } = require('./blogs');
// 解析请求体中的JSON数据
app.use(express.json());
// 设置路由
app.post('/api/blogs/add', addBlogs);
// 启动服务器
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
数据库操作模块(db.js):
const mysql = require('mysql');
// 创建数据库连接
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'database_name'
});
// 连接数据库
db.connect(err => {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database');
});
module.exports = db;
博客接口模块(blogs.js):
const db = require('./db');
exports.addBlogs = (req, res) => {
const info = req.body;
const sqlStr = `select * from blogs_info where title = ?`;
db.query(sqlStr, info.title, (err, results) => {
if (err) return res.cc(err);
if (results.length === 1) return res.cc("已存在相同标题的文章,请更换!");
})
const sql = `insert into blogs_info set ?`;
db.query(sql, { title: info.title, author: info.author, classify: info.classify }, (err, results) => {
if (err) return res.cc(err);
if (results.affectedRows !== 1) return res.cc("新增文章失败!");
res.cc("新增文章成功", 0);
});
}
前端HTML文件(index.html):
<div>
<form action="/api/blogs/add" method="post">
<table>
<tr>
<td>博客标题:</td>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<td>作者:</td>
<td><input type="text" name="author" value=""></td>
</tr>
<tr>
<td>分类:</td>
<td>
<select name="classify" id="">
<option value="1">后端开发</option>
<option value="2">前端开发</option>
<option value="3">软件工程</option>
<option value="4">数据库</option>
</select>
</td>
</tr>
<tr>
<td><input id="btnSave" type="submit" value="保存"></td>
<td><input id="btnCancel" type="reset" value="取消"></td>
</tr>
</table>
</form>
</div>
<script>
document.getElementById("btnCancel").addEventListener("click",() => {
location.href = "./index.html";
});
</script>
以上代码将Node.js的接口和前端的HTML文件进行了对接,当在前端页面点击保存按钮时,将会向"http://localhost:3000/api/blogs/add"发送POST请求,并调用addBlogs函数来处理该请求
原文地址: http://www.cveoy.top/t/topic/h1Y9 著作权归作者所有。请勿转载和采集!