英文:
Data read from the db using the endpoint appears as undefined
问题
我使用了在 https://stackoverflow.com/a/70799801 找到的第二种方法,并将其应用到我的源代码中。
我目前正在使用的 SvelteKit 版本是 1.0.0-next.73。
然而,当我将数据打印到控制台时,我只能看到 undefined
。
下面是我的源代码:
/lib/db/mysql.js
import mysql from 'mysql2/promise';
let mysqlconn = null;
export function mysqlconnFn() {
if (!mysqlconn) {
mysqlconn = mysql.createConnection({
host: 'localhost',
port: 3307,
user: 'dbuser',
password: 'dbpassword',
database: 'dbname'
});
}
return mysqlconn;
}
/routes/index.server.js
import { mysqlconnFn } from '$lib/db/mysql';
export async function get() {
let mysqlconn = await mysqlconnFn();
let results = await mysqlconn.query('SELECT * FROM list_user')
.then(function ([rows, fields]) {
// console.log(rows);
return rows;
})
.catch(() => {
console.log("err")
})
return { results }
}
/routes/index.svelte
<script>
export let data
import { onMount } from "svelte"
onMount(() => {
console.log(data)
});
</script>
如果您能告诉我出了什么问题以及如何解决,我将不胜感激。
英文:
I used the second method found at https://stackoverflow.com/a/70799801 and applied it to my source.
The version of sveltekit I am currently using is 1.0.0-next.73.
However, when I printed the data to the console, I could only see undefined
.
Below is my source code:
/lib/db/mysql.js
import mysql from 'mysql2/promise';
let mysqlconn = null;
export function mysqlconnFn() {
if (!mysqlconn) {
mysqlconn = mysql.createConnection({
host: 'localhost',
port: 3307,
user: 'dbuser',
password: 'dbpassword',
database: 'dbname'
});
}
return mysqlconn;
}
/routes/index.server.js
import { mysqlconnFn } from '$lib/db/mysql';
export async function get() {
let mysqlconn = await mysqlconnFn();
let results = await mysqlconn.query('SELECT * FROM list_user')
.then(function ([rows, fields]) {
// console.log(rows);
return rows;
})
.catch(() => {
console.log("err")
})
return { results }
}
/routes/index.svelte
<script>
export let data
import { onMount } from "svelte"
onMount(() => {
console.log(data)
});
</script>
I'd be grateful if you could tell me where I went wrong and how to fix it.
答案1
得分: 1
Files in routes have to be called:
+page.svelte
+page.js
/ts
+page.server.js
/ts
+server.js
/ts
So not index
, also if you want data to load, the function (in +page.server.js
/ts
) has to be called load
.
英文:
Files in routes have to be called:
+page.svelte
+page.js
/ts
+page.server.js
/ts
+server.js
/ts
So not index
, also if you want data to load, the function (in +page.server.js
/ts
) has to be called load
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论