JERRY_LIU 2025-05-30 11:55 采纳率: 83.3%
浏览 15
已结题

网页前端js 调用带参数的后端接口时,提示err_unknown_url_scheme

写了两个后端的代码,在网页中调用正常,但是写了一个前面页面来调用,一直报错。

/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
    })
}

还是一样的错误代码,不知道是哪里的问题?

  • 写回答

3条回答 默认 最新

  • 檀越@新空间 2025-05-30 11:56
    关注

    上午好☀️☀️☀️️
    本答案参考通义千问

    从你的描述来看,问题的核心在于前端页面通过 uni.request 调用后端接口时,出现了 net::ERR_UNKNOWN_URL_SCHEME 错误。这种错误通常与 URL 格式或协议有关。以下是详细的分析和解决方案:


    问题分析

    1. 错误原因

      • net::ERR_UNKNOWN_URL_SCHEME 表示浏览器无法解析 URL 的协议部分。
      • 在你的代码中,url 参数被设置为 "localhost:3000/api/data/198""localhost:3000/api/data",缺少协议(如 http://https://)。
      • 浏览器默认会尝试解析为文件系统路径或其他非标准协议,导致错误。
    2. 关键点

      • uni.request 是 UniApp 框架中的网络请求 API,它要求完整的 URL 格式。
      • 如果你在本地开发环境中使用 localhost,必须明确指定协议(如 http://)。
      • 同时,uni.requestdata 参数需要正确传递查询参数。

    解决方案

    以下是解决问题的具体步骤和代码修改建议:

    1. 修改 URL 格式

    确保 url 参数包含完整的协议(如 http://https://)。例如:

    function request() {
        uni.request({
            url: "http://localhost:3000/api/data/198", // 添加协议
        }).then(res => {
            arrs.value = res.data;
        });
    }
    

    或者使用查询字符串:

    function request() {
        uni.request({
            url: "http://localhost:3000/api/data", // 添加协议
            data: { id: 198 }, // 使用 data 参数传递查询参数
        }).then(res => {
            arrs.value = res.data;
        });
    }
    

    2. 确保后端接口支持查询参数

    虽然你提到后端接口可以通过 /api/data/:id/api/data?id=198 两种方式正常工作,但仍需确认后端是否正确处理了查询参数。以下是对后端代码的检查和优化:

    • 后端代码检查

      • 确保 app.get('/api/data') 路由能够正确解析查询参数。
      • 示例代码已经支持两种方式(路径参数和查询字符串),无需额外修改。
    • 后端日志验证

      • executeQuery 函数中添加日志,打印传入的 id 值,确保后端接收到正确的参数:
        function executeQuery(id, res) {
            console.log('Received ID:', id); // 添加日志
            new sql.Request()
              .input('id', sql.Int, id)
              .query(sqlScript)
              .then(result => {
                res.json(result.recordset);
              })
              .catch(err => {
                console.error('SQL查询错误:', err);
                res.status(500).send({ message: 'Server error' });
              });
        }
        

    3. 检查前端框架环境

    UniApp 是一个跨平台框架,某些情况下可能会对 URL 格式有特殊要求。以下是一些额外的注意事项:

    • 避免使用相对路径

      • 确保 url 参数始终是绝对路径,而不是相对路径。
    • 检查跨域问题

      • 如果后端和前端运行在不同的域名或端口上,确保后端启用了 CORS(跨域资源共享)。
      • 在 Express 中启用 CORS 的示例代码:
        const cors = require('cors');
        app.use(cors());
        
    • 调试工具

      • 使用浏览器开发者工具查看网络请求,确认请求是否成功发送到后端。

    4. 修改后的完整代码

    以下是修改后的前端代码示例:

    <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>
    import { ref } from 'vue';
    
    let arrs = ref([]);
    
    function request() {
        uni.request({
            url: "http://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>
    

    总结

    通过以上步骤,你应该可以解决 net::ERR_UNKNOWN_URL_SCHEME 错误。关键点在于确保 url 参数包含完整的协议(如 http://),并且正确传递查询参数。如果问题仍然存在,请进一步检查后端日志和网络请求的详细信息。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 6月7日
  • 已采纳回答 5月30日
  • 创建了问题 5月30日