写了两个后端的代码,在网页中调用正常,但是写了一个前面页面来调用,一直报错。
/db/index.js档案,数据库配置
const config = {
server: '192.168.2.4',
database: 'database',
user: 'sa',
password: 'xxxxxxxx',
port: 1433,
options: {
trustedConnection: true,
},
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000,
},
options: {
encrypt: false,
},
};
module.exports = {
config
// 输出数据库配置
};
start.js档案, 连接mssql , 并执行查询:
```javascript
const express = require('express');
const sql = require('mssql');
const str = require('./db/index');
// 创建Express应用
const app = express();
const sqlScript = 'Select column1, column2, column3 From table where id = @id'
// 连接数据库
sql.connect(str.config).then(() => {
console.log('数据库连接成功');
//跨域资源共享
// 定义API路由
app.get('/api/data/:id', (req, res) => {
// 执行SQL查询
new sql.Request()
.input('id', req.params.id)//接收Api参数,传递给sqlScript参数@id
.query(sqlScript)
.then(result => {
// 将查询结果返回给API
res.json(result.recordset);
})
.catch(err => {
// 错误处理
console.error('SQL查询错误:', err);
res.status(500).send({ message: 'Server error' });
});
});
// 监听端口
const port = 3000;
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
}).catch(err => {
console.error('数据库连接失败:', err);
});
在cmd 窗口中执行node start.js,启动后端服务,然后在浏览器中输入网址:
http://localhost:3000/api/data/198
198是ID值,此时可以正常返回数据库的查询内容。
如果把网址改为:http://localhost:3000/api/data?id=198 ,此时返回 Cannot GET /api/data
不知道是哪里写错了,有没有高手帮忙看一下。谢谢!