node.js 代码在浏览器中使用 localhost URL 打开页面

Posted

技术标签:

【中文标题】node.js 代码在浏览器中使用 localhost URL 打开页面【英文标题】:node.js code to open a page in browser with 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

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

【问题讨论】:

这有帮助吗? Open a URL via the operating system 是的,这可能会有所帮助,我会调查一下!谢谢 【参考方案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 非常有用。

【讨论】:

以上是关于node.js 代码在浏览器中使用 localhost URL 打开页面的主要内容,如果未能解决你的问题,请参考以下文章

包含 Node.JS (vue) 的文件

如何在 Node.js 和浏览器之间共享代码?

如何在没有浏览器的 node.js 中使用 FormData?

使用Jasmine和node.js测试客户端javascript代码

node.js,mongodb,mongoose,html 我如何插入数据(在 index.html 中)?

使Node.js中的http.request适用于浏览器