【问题标题】:localhost replies with CANNOT GET/localhost 回复 CANNOT GET/
【发布时间】:2021-12-30 21:18:09
【问题描述】:

这是我的代码

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

const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());

const cors = require('cors');
app.use(cors());

app.use(express.static('website'));

const port = 8000;
const server = app.listen(port, () => {
    console.log('the server is up and running');
    console.log(`in a localhost ${port}`);
})

我把它链接到有代码的html页面

<!DOCTYPE html>
<html lang="en"> 
    
    
    <head>
        
        <meta charset="UTF-8">
        
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        
        <title> Hello World!</title>
        
        
        
        <script src='L2Server.js' >  </script>

    </head>

    <body>

<p>Hi!</p>



<script src='L2Server.js' ></script>
    </body>

  





</html>

当我在终端中运行代码时,它显示服务器已启动并正在运行,然后当我在浏览器中打开 localhost 时,它会显示一条带有以下“CANNOT GET/”的消息,我尝试了几乎所有方法来解决这个问题问题,但我不知道是怎么回事。

【问题讨论】:

    标签: javascript node.js server localhost


    【解决方案1】:

    你需要定义一个类似的路由

    app.get('/', function(req, res) {
      // set response here
    });
    

    或从文件夹中提供静态内容

    app.use(express.static(__dirname + '/public'));
    

    在您的情况下,将您的 html 代码放在 ./public/index.html 中并将其作为静态内容提供。

    【讨论】:

    • 我用过这个 app.use(express.static('website'));这是什么意思,因为我已经在代码中输入了它,我尝试了上面的方法,它没有工作
    • 您必须提供目录的绝对路径。 __dirname + '/public' 创建一个相对于 .js 文件的绝对路径。 __dirname 是包含您的 .js 文件的目录的路径。
    • 抱歉,您能否给我看一个代码示例,因为我不明白您写的句子中间的加号,我应该把它写在代码中吗?如果你能告诉我一个例子
    • + 符号连接两个字符串。 __dirname + '/public' 创建一个字符串,其中包含公共文件夹的绝对路径,相对于您的 .js 文件创建。如果您有一个包含 .js 文件的文件夹“yourproject”和一个子目录“public”,这将提供“public”的内容作为静态内容。现在将您的 html 文件 (test.html) 放入公共文件夹并导航到 http://localhost:3000/test.html
    【解决方案2】:

    添加如下内容:

    app.get('/', (req, res) => {
        res.send('website');
    });
    

    其中“网站”是您的 html 的名称

    【讨论】:

    • 我的名为 index 的 html 文件,当我执行您所引用的操作时,它显示了单词 index 并且没有执行我在上面发布代码的 html 文件中的内容
    • 当我使用 sendFile 方法并使用文件的绝对路径执行此操作时,它会显示此消息a 和一些其他错误“TypeError: path must be absolute or specified root to res.sendFile "
    • 你试过了吗:app.get('/', (req, res) => { res.sendFile('website', { root: '.' }); });跨度>
    猜你喜欢
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多