问题描述
我在Express中有以下代码,该代码重定向到views / index.html页面。现在,我也想在此代码中执行某些函数后立即将一些整数发送到index.html。最快的方法是什么?
function graphQLPost(string $endpoint,string $query,array $variables = [],?string $token = null)
{
$payload = json_encode(['query' => $query,'variables' => $variables]);
$headers = array();
if ($token != null) {
$headers[] = "Content-Type: application/json\r\n" .
'Authorization: Bearer ' . $token;
} else
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$endpoint);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);
curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
// Submit the POST request
$resultJson = curl_exec($ch);
$httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
// Close cURL session handle
curl_close($ch);
return array($resultJson,$httpcode);
}
// definiamo la mutation
$mutation = '
mutation createClients($project_id: ID!,$input: ClientInput!) {
createClients(project_id: $project_id,input: $input) {
id
firstName
lastName
tel
email
trattamento
profilazione
marketing
}
} ';
// parametri da passare come argomenti
$param = [
'project_id' => $PROJECT_ID,'input' => array(
'firstName' => $nome,'lastName' => $cognome,'email' => $email,'tel' => $telefono,'trattamento' => $trattamento_DB,'profilazione' => $profilazione_DB,'marketing' => $marketing_DB,'status' => 'lead',)
];
// esecuzione del comando
$response = graphQLPost($API_URI,$mutation,$param,$TOKEN);
解决方法
我个人会使用一个“ ejs”文件。
安装:
npm install ejs --save
然后在您的index.js中将代码更改为:
const app = express()
app.set('view engine','ejs'); //support ejs files
app.get('/',function(req,res) {
res.render('index.ejs',{varableName: varablePath}) //make sure your index.ejs is in your "views" folder
});
app.listen(3000);
然后在新的 ejs 文件中,使用以下行:<%= varableName %>
跨文件导入变量
您需要使用EJS / Jade之类的模板引擎来做到这一点:
-
首先,通过运行以下命令将其添加到项目中:
npm install ejs --save
-
将html页面转换为ejs页面。
-
在Express Server应用程序中使用以下行:
app.set('view engine','ejs');
-
使用render方法发送javascript变量。例如:
res.render('index',{title:“主页”,计数器:1});
-
现在,在 index.ejs 文件中,根据需要在以下位置读取值
计数器:,