写了两个后端的代码,在网页中调用正常,但是写了一个前面页面来调用,一直报错。
/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 , 并执行查询:
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) => {
const id = req.params.id; // 优先使用路径参数
executeQuery(id, res);
});
app.get('/api/data', (req, res) => {
const id = req.query.id; // 如果路径参数不存在,则使用查询字符串参数
if (!id) {
return res.status(400).send({ message: 'Missing "id" parameter' });
}
executeQuery(id, res);
});
// 执行SQL查询的通用函数
function executeQuery(id, res) {
new sql.Request()
.input('id', sql.Int, id) // 设置SQL参数类型为整数
.query(sqlScript)
.then(result => {
// 返回查询结果
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 或者 http://localhost:3000/api/data?id=198
198是ID值,两种方式都可以正常返回数据库的查询内容
但是如果用我写的前端页面来调用,就出错了。这里是前端页面的代码:
<template>
<view class="layout">
<view class ="row" v-for="item in arrs" :key="item.sid">
<view class="title">{{item.xUserName}}</view>
<view class="body">{{item.xUserCode}}</view>
</view>
</view>
</template>
<script setup>
let arrs = ref([])
function request(){
uni.request({
url:"localhost:3000/api/data/198"
}).then (res=>{
arrs.value = res.data
})
}
request();
</script>
<style lang="scss" scoped>
.layout{
padding:30rpx;
.row{
border-bottom: #cfcfcf;
padding:20rpx 0;
.title{
font-size: 36rpx;
margin-bottom: 10;
}
}
}
</style>
网页地址为:http://localhost:5173/#/pages/searchdemo/search-hr
打开这个网页时,报错如下:
search-hr.vue:16
GET localhost:3000/api/data/198 net::ERR_UNKNOWN_URL_SCHEME
request @ search-hr.vue:16
setup @ search-hr.vue:22
Promise.then (async)
(anonymous) @ main.js:22
Show 101 more frames
我试着改了网页内的URL地址: "localhost:3000/api/data?id=198 一样报错。
我再试着将前端的request function改了一下:
function request(){
uni.request({
url:"localhost:3000/api/data",
data:{
id:198
}
}).then (res=>{
arrs.value = res.data
})
}
还是一样的错误代码,不知道是哪里的问题?