首页 > 解决方案 > SyntaxError:在 require("file_path") 语句上出现意外的标记 '<'

问题描述

在我的 node.js 应用程序中,我从请求中返回了一些 HTML。我正在使用 express,所以我使用 require() 语句将其放入变量中并随请求返回。这一切都很好,直到突然停止工作,而我没有故意改变任何东西。

错误

<!DOCTYPE html>
^

SyntaxError: Unexpected token '<'
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (path/controllers/homepage.js)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (path/routes/home.js)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)

我已将罪魁祸首代码隔离到以下第一行:

const page = require("../Front End/Index.html");

exports.getHome = (req, res) => {
    res.sendFile(page);
}

关于堆栈溢出的其他问题指向 HTML 文件有问题,所以下面是段(也是错误指向的地方)

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="Index.css">
    <title>Wildfire</title>
    <link rel="icon" href="Assets/wildfirelogo64.png">
</head>

我究竟做错了什么?

标签: javascriptnode.js

解决方案


You can not require an html file, HTML syntax cannot execute as a JS syntax.

If you want to send an HTML file to the client with express application, just follow some simple example on the internet:


exports.getHome = (req, res) => {
    res.sendFile("../Front End/Index.html"); // send it
}

推荐阅读