【问题标题】:How to use mysql2 library with Sapper?如何在 Sapper 中使用 mysql2 库?
【发布时间】:2021-11-14 08:00:32
【问题描述】:

我正在 Svelte Sapper 中创建一个应用程序。我有一个routes/account/login.js API 路由,我正在尝试使用mysql2。路由本身是有效的(我用 Postman 查过),但是一导入 mysql,服务器就崩溃并出现错误:

[rollup-plugin-svelte] The following packages did not export their `package.json` file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.

- mysql2
import mysql from "mysql2/promise";

export async function post(req, res) {
  //route test
  const { login, password } = req.body;
  res.end(`${login}, ${password}`);
}

我该怎么做才能使这个导入工作? 我该怎么做才能使这个导入工作?

Sapper 文档没有说明您是否需要另外更改配置中的某些内容。 https://sapper.svelte.dev/docs#Server_routes

【问题讨论】:

    标签: node.js svelte rollup sapper node-mysql2


    【解决方案1】:

    我找到了解决方案。我必须在src/node_modules 文件夹中创建一个@lib 文件夹,并在其中创建文件,例如。 db.js。在该文件而不是import 中,您需要使用require()!然后你必须导出连接到数据库的函数。然后你可以在路径中导入它

    //src/node_modules/@lib/db.js
    const mysql = require("mysql2");
    
    export async function connectToDatabase() {
      return mysql.createConnection({
        host: "localhost",
        ....
      })
    }
    
    //routes/account/login.js
    import { query } from "@lib/db";
    export async function post(req, res) {
      ...
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-09
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2021-02-25
      • 2020-04-09
      • 1970-01-01
      相关资源
      最近更新 更多