You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入oracledb遇MIME类型错误,ES6模块等方案无效求助

解决浏览器端导入oracledb报错及前端值传递问题

一、核心问题:oracledb不能在浏览器环境运行

oracledb是Node.js专属的后端数据库驱动,仅能在Node.js环境下执行数据库操作,浏览器不具备Node.js的模块系统和底层API支持,直接在前端导入必然报错。你导入的@types/oracledb只是TypeScript类型定义文件,并非实际可执行的驱动代码,即便能导入也无法完成数据库操作。

二、MIME类型错误的直接原因

你写的导入路径../node_modules/@types/oracledb在浏览器中无法正确解析:

  • 绝大多数开发服务器不会将node_modules目录暴露给前端访问,请求该路径会返回404错误,服务器通常会把404页面(HTML)返回,导致MIME类型为text/html,触发"预期为JavaScript模块脚本"的报错。
  • 即使能访问到类型定义文件,它也不是可执行的JS模块,同样会引发错误。

三、正确的架构方案

必须将数据库操作放在Node.js后端,前端通过HTTP请求与后端API交互,具体步骤如下:

1. 搭建Node.js后端服务

创建基于Express的简单后端,处理数据库连接与车票注册逻辑:

// backend/server.js
const express = require('express');
const oracledb = require('oracledb');
const cors = require('cors');
const app = express();
const port = 3000;

// 解决跨域问题
app.use(cors());
// 解析JSON请求体
app.use(express.json());

// 初始化Oracle客户端(若本地Oracle环境需要配置)
// oracledb.initOracleClient({ libDir: '你的Oracle客户端安装路径' });

// 获取数据库连接
async function getConexao() {
    try {
        return await oracledb.getConnection({ 
            user: "SYSTEM", 
            password: "ospiri", 
            connectionString: "localhost/xe" 
        });
    } catch(erro) {
        console.error('数据库连接失败:', erro);
        return null;
    }
}

// 初始化车票表(仅需执行一次)
async function initBilhetesTable() {
    const conexao = await getConexao();
    if (!conexao) return;
    const sql = `CREATE TABLE IF NOT EXISTS bilhetes (
        cod_bilhete NUMBER(20),
        data_geracao DATE,
        hora_geracao TIMESTAMP,
        PRIMARY KEY (cod_bilhete)
    )`;
    try {
        await conexao.execute(sql);
        await conexao.commit();
        console.log('车票表初始化完成');
    } catch(erro) {
        console.error('表初始化失败:', erro);
    } finally {
        if (conexao) await conexao.close();
    }
}

initBilhetesTable();

// 接收前端车票注册请求
app.post('/registrar-bilhete', async (req, res) => {
    const { codBilhete } = req.body;
    if (!codBilhete) return res.status(400).send('缺少车票编号');

    const conexao = await getConexao();
    if (!conexao) return res.status(500).send('数据库连接失败');

    try {
        const sql = `INSERT INTO bilhetes (cod_bilhete, data_geracao, hora_geracao) 
                     VALUES (:cod, SYSDATE, SYSTIMESTAMP)`;
        await conexao.execute(sql, { cod: codBilhete });
        await conexao.commit();
        res.status(200).send('车票注册成功');
    } catch(erro) {
        console.error('注册失败:', erro);
        res.status(500).send('注册失败,该车票编号已存在');
    } finally {
        if (conexao) await conexao.close();
    }
});

app.listen(port, () => {
    console.log(`后端服务运行在 http://localhost:${port}`);
});

2. 前端修改:移除oracledb导入,改用API交互

更新前端JS模块(index.js),去掉数据库操作逻辑,改为调用后端API:

// index.js
export async function registrarBilhete(codBilhete) {
    try {
        const response = await fetch('http://localhost:3000/registrar-bilhete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ codBilhete })
        });
        return await response.text();
    } catch(erro) {
        return `请求失败:${erro.message}`;
    }
}

3. 前端传递resultado到模块

修改HTML代码,用DOM操作替代document.write,并实现值传递与表单提交逻辑:

<div class="main-content-label"> 
    <div id="codigo-bilhete"></div>
    <form id="registro-form">
        <input type="number" name="bilhete" id="input-bilhete"><br>
        <small>Digite seu código para registrá-lo!</small><br>
        <button type="submit">Registrar</button>
    </form>
    <script type="module">
        // 生成车票编号
        const bilhetes = [];
        function sorteio() { 
            return Math.floor(Math.random() * 999999);
        }
        let resultado;
        while(bilhetes.length < 1) {
            resultado = sorteio();
            if(bilhetes.indexOf(resultado) === -1){
                bilhetes.push(resultado);
            }
        }
        // 显示生成的编号
        document.getElementById('codigo-bilhete').textContent = `Seu código é : ${resultado}`;
        // 自动填充到输入框(可选)
        document.getElementById('input-bilhete').value = resultado;

        // 导入模块并绑定提交事件
        import { registrarBilhete } from '../index.js';
        document.getElementById('registro-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const cod = document.getElementById('input-bilhete').value;
            const mensagem = await registrarBilhete(cod);
            alert(mensagem);
        });
    </script>
</div>

四、MIME类型错误的补充排查

若仍出现MIME类型错误,检查以下内容:

  • 必须用开发服务器(如http-server、live-server)打开HTML,禁止直接双击本地文件使用file://协议,该协议不支持ES模块加载。
  • 确认JS文件路径正确,服务器能正常返回JS文件(MIME类型为application/javascript)。

内容的提问来源于stack exchange,提问作者KauanBS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:05:22