【问题标题】:node.js code to open a page in browser with localhost URLnode.js 代码在浏览器中使用 localhost URL 打开页面
【发布时间】:2015-07-01 03:39:24
【问题描述】:

我使用 node.js 编写了一个简单的服务器。目前,服务器通过向浏览器写入“hello world”来响应。

server.js 文件如下所示:

var http = require("http");
http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8080);

我在浏览器中使用这个 URL 来触发“hello world”响应:

http://localhost:8080/

当我传递这样的 URL 时,我希望能够打开一个基本的 html 页面:

http://localhost:8080/test.html

我浏览了许多教程和一些 stackoverflow 帖子,但关于这个特定任务的内容并不多。有谁知道如何通过对 server.js 文件的简单修改来实现这一点?

【问题讨论】:

标签: html node.js url browser server


【解决方案1】:

如果你想借助“http://localhost:8080/test.html”这样的url通过nodejs打开.html文件,需要将.html页面转换为.jade格式。使用渲染引擎配合expressjs框架。express渲染引擎将帮助您在 nodejs 服务器上呈现 .jade 文件。

【讨论】:

  • 这很复杂,但是,它可能是最干净的方法。我会调查的。谢谢。
【解决方案2】:

最好使用 Angular、React 或 Vue 等前端 javascript 框架来路由到不同的页面。不过,如果您想在 Node 中执行此操作,您可以使用 express 执行以下操作:

var express = require('express');
var app = express();
app.get('/', function(req, res) {
  res.sendFile('views/index.html', { root: __dirname })
});
app.get('/test', function(req, res) {
  res.sendFile('views/test.html', { root: __dirname })
});
app.listen(8080);

这对于静态页面来说是一个不错的解决方案。 Express 对于编写 REST API 非常有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2018-06-20
    • 2012-04-21
    相关资源
    最近更新 更多