如何将mySQL数据库(在不支持Node.js的主机上)连接到React应用程序(js)



需要您的支持和帮助问题:主机提供商不支持Node.JS(只是购买了另一个我不想做的托管计划(我使用的是:React App(Javascript(,还包了"mysql"one_answers"express",不幸的是,对PHP语言的了解很低(时间问题(。我很熟悉如何使用Node.JS进行连接(在非常基础的级别(。

问题(我猜是简单的问题(:是否可以使用Java Script(React App(连接位于不支持Node.js的主机上的mySQL数据库?以及如何使用从mySQL检索到的数据?

非常感谢。

如果没有php等服务器端语言,就无法直接将react作为前端语言连接到服务器上的mysql数据库。使用php端点,您可以使用mysqli连接到要连接的服务器上的mysql数据库。

您需要使用以下表格:

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
//accepts cors access from all locations
header('Access-Control-Allow-Origin: *');  
header('Access-Control-Allow-Headers: *');

//login to your mysql db

$hn = 'localhost';
//The below change
$db = 'dbname';
$pw = 'yourpassword';
$un = 'root';

$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die("Can't Connect");

//the rest are called prepared statements
$query = 'select id from accounts where name=?';
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $input);

$input = "someValue";// $_GET['input'];

$result = $stmt->execute();
$stmt->bind_result($idOut);
$stmt->fetch();
$stmt->close();
return $idOut;
elseif($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
// this allows react to not explode on cors preflight        
}

最新更新