[英]Next.js Error: Cannot read properties of undefined (reading 'call'), try/catch won't work onClick?
var mysql = require("mysql");
import React from "react";
export async function mySqlQuery(myQuery) {
try {
console.log("Running query...");
var connection = mysql.createConnection({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USERNAME,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
});
connection.connect();
connection.query(myQuery, function (error, results) {
if (error) throw error;
const output = results[0].solution;
console.log(output);
});
connection.end();
} catch (e) {
console.error(e.message); // or "throw Error(e.message)", this shows it directly on top of the webpage
}
}
The button i use to call the function (without the () =>
Next.js thinks it's an object)我用来调用 function 的按钮(没有() =>
Next.js 认为它是一个对象)
<button onClick={() => mySqlQuery("SELECT 1 + 190 / 2 AS solution;")}> SQL PUSH </button>
I tried this too我也试过这个
<button onClick={async () => await mySqlQuery("SELECT 1 + 190 / 2 AS solution;") } > SQL PUSH </button>
I get the following error: Uncaught (in promise) Error: Cannot read properties of undefined (reading 'call')
我收到以下错误: Uncaught (in promise) Error: Cannot read properties of undefined (reading 'call')
This is the error in the DevTools console:这是 DevTools 控制台中的错误:
This is the error in Next.js, when i use throw Error()
.这是 Next.js 中的错误,当我使用throw Error()
时。
The code inside the try
block is erroring, and you're seeing the error being caught/thrown in the catch
block. try
块内的代码出错,您会看到在catch
块中捕获/抛出错误。
mysql
is a Node.js package, it can't be used on the client-side in the browser. mysql
是 Node.js package,不能在浏览器的客户端使用。 You have to move the logic to the backend or to an API route, then make a request against that on the client-side.您必须将逻辑移动到后端或 API 路由,然后在客户端发出请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.