【问题标题】:How to get value from php variable in node.js如何从 node.js 中的 php 变量中获取值
【发布时间】:2016-12-05 16:33:43
【问题描述】:

我正在开发一个项目考勤系统,我想访问在我的 node.js 文件 custom.js 中的 php 文件 require.php 中声明的变量我应该如何实现?到目前为止,我已经创建了与我的 sql 服务器的连接并硬编码了的值

`var company_name="Aaqoo 2";`

并且一切正常,但我不想对其进行硬编码$sup_company_name 在我的 js 变量中......请帮助我,然后我会问更多问题

这是我的节点 js 代码

var express = require('express');
var mysql = require('mysql');
var app = express();

var connection = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'',
    database:'attendance'
});

connection.connect(function(error) {
    if (!!error) {
    console.log('Error in connection');
    } else {
    console.log('Connected');  
    }
});
var company_name = "Aaqoo 2"; //here i want the value from php variable $sup_company_name;

connection.query("Select * from employee_leaves where employee_leave_company_name=?", [company_name], function(error,rows,fields) {
    if (!!error) {
        console.log("Error in the query");
    } else {
        console.log("succesfully done\n");
        console.log(rows);
    }
});

app.listen(1337);

【问题讨论】:

  • 你试过了吗? var company_name= '<?php echo $sup_company_name; ?>'
  • @Oluwafemi 但问题是 $sup_company_name 在 require.php 文件中,当我使用 include("require.php"); 包含 require php 文件时; node.js 给我错误
  • 错误是什么?
  • PHP 在 JavaScript 之前执行。首先通过 PHP 包含您的 PHP 文件,然后回显变量值
  • @Oluwafemi SyntaxError: Unexpected token ?> 在 Export.runInThisContext (vm.js:53:16) 在 Module._compile (module.js:373:25) 在 Object.Module._extensions..js (module.js:416:10) 在 Module.load (module.js:343:32) 在 Function.Module._load (module.js:300:12) 在 Function.Module.runMain (module.js:441:10) 在启动时 (node.js:139:18)在 node.js:968:3

标签: javascript php node.js


【解决方案1】:

我做到了,这是我的例子,只是我将它用于我与 pgsql 的连接。

代码节点js

var exec = require('child_process').exec;

exec(
    'php -r \'include("require.php"); echo $companyname."#@#".$hostname."#@#".$username."#@#".$database."#@#".$password;\'',

  function (err, stdout, stderr) {
    var [ companyname,hostname,username, database, password ] = stdout.split('#@#');
    const connectionData = {
      user: username,
      host: '',
      database: database,
      password: password,
      port: 5432,
    }
    const client = new Client(connectionData)

    client.connect()
    client.query('Select * from employee_leaves where employee_leave_company_name=?',companyname)
        .then(response => {
            //console.log(response.rows)
            client.end()
        })
        .catch(err => {
            client.end()
        })
  }
);

require.php


$companyname= 'namecompany'; 
$hostname = 'localhost';
$database = 'namedatabase';
$username = 'root';
$password = '123';

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多