【问题标题】:Javascript and HTML ProblemsJavascript 和 HTML 问题
【发布时间】:2018-03-15 05:48:34
【问题描述】:

无法让它与节点一起运行

const express = require('express')
const app = express()

app.use(express.static('public')) //adds content of public folder

app.get('/', function (req, res){
       res.sendFile('/views/index.html', {root: __dirname})
})

app.listen(1337, function (){
    console.log('lab5-server.js listening on 1337')
})

昨天运行得很完美,现在却不行了。 .html 部分也有问题,它不会显示我分配的图像。请注意,我遗漏了图像源代码下方的大部分内容,这个问题没有必要。

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1> <center> Welcome to Matt's Page </center></h1>

<center> <img src = "images/AlgorithmofSuccess.jpg"/> </center>

有谁知道我哪里出错了,为什么终端在 javascript 部分返回“意外令牌”?

【问题讨论】:

  • 如果仅此而已,__dirname 未定义
  • “为什么终端在 javascript 部分返回“意外的令牌””——不是
  • 我们可以改进一下这个标题吗?
  • 确定你想让我怎么改?

标签: javascript html node.js


【解决方案1】:

我解决了这个问题,只需要更改我正在使用的 lab5-server.js 文件的文件夹,感谢大家的帮助

【讨论】:

    【解决方案2】:

    您应该尝试使用path 模块来帮助指向您的公共路径。我可以举个例子:

    const path = require("path");
    const app = express();
    const publicPath = path.resolve(__dirname, "./public");
    
    // We point to our static assets
    app.use(express.static(path.resolve(__dirname, "./public")));
    
    app.get("/*", (req, res) => {
      res.sendFile("index.html", { root: path.join(__dirname, "./public") });
    });
    
    // And run the server
    app.listen(1337, () => {
      console.log(`Server running on port ${port}`);
    });
    

    确保./public./dist 路径包含您的index.html

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 1970-01-01
      • 2014-07-04
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多