0

我正在 Svelte Sapper 中创建一个应用程序。我有一个routes/account/login.jsAPI 路由,我正在尝试使用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

4

1 回答 1

0

我找到了解决方案。我必须在文件夹中创建一个@lib文件src/node_modules夹,并在那里创建文件,例如。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) {
  ...
}

于 2021-09-20T16:40:54.843 回答