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)
<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')
The code inside the try
block is erroring, and you're seeing the error being caught/thrown in the catch
block.
mysql
is a Node.js package, it can't be used on the client-side in the browser. You have to move the logic to the backend or to an API route, then make a request against that on the client-side.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.