元标记服务器端呈现

meta tag server side rendering

我正在使用 react helmet 并且对服务器端呈现有点迷茫。如果我在 google 控制台中查看元素,我可以看到标题和元描述,但在查看页面源时它们不存在。

我正在使用带有 express 的 Node.js 后端来创建 API。 React 应用程序只是一个前端应用程序,它从 Node.js API 获取数据。

在 React 中我只需要:

import { Helmet } from "react-helmet";
render() {
   return(
      <>
        <Helmet>
          <title>My site title</title>
          <meta name="description" content="Helmet application" />
        </Helmet>
      </>
    )
}

服务器端示例的 direct link 显示了一些我真的不知道如何处理的代码。我认为 'server' 这个词让我失望,因为我认为我需要在我的 Node.js 服务器上放置一些代码,但也许情况并非如此?

事实上,Helmet.renderStatic() 方法将收集与您请求的页面对应的所有标签。

如果你想在服务器端也看到这些标签(源代码),你需要在你的服务器文件中:

  1. 调用const helmet = Helmet.renderStatic()

  2. helmet得到helmet.title.toString()helmet.meta.toString()

  3. 将这些附加到您的 HTML 就像 https://github.com/nfl/react-helmet#server-usage As string input 描述的那样。

index.html改为index.php并在中使用PHP index.php 构建后。并创建一个文件 myMata.php 将所有旧元标记移动到 myMata.php 并使用 PHP.

制作动态元标记

view-source:https://www.heinsoe.com

index.php

<html>
    <head>
    <?php include './myMata.php';?>
    //more code

myMata.php

<?php
$path =  parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$paths = (explode("/", $path));
if (isset($paths[1])) {
    switch ($paths[1]) {
        case 'blog':
            ?>
            <title>dynamic title</title>
            //..... other tag
            <?php
            break;
        case 'contact':
            ?>
            <title>contact</title>
            //..... other tag
            <?php
            break;
        default:
            http_response_code(404);
            break;
    }
}
else{ 
    ?>
    <title>Home</title>
    //..... other tag
    <?php
}
?>