node.js 代码使用本地主机 URL 在浏览器中打开页面

问题描述 投票:0回答:3

我使用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
3个回答
0
投票
yarn add express open
import open from 'open';
import express from 'express';

const port = 3000;
const app = express();

app.get('/', async (req, res) => {
  res.send('Hello, Coder!');
});

app.listen(port, () => {
  console.log(`listen port: ${port}`);
  open(`http://localhost:${port}`)
});

第二种变体:

const http = require('http');
const open = require('open');

const PORT = 3000;

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<h1>Hello World!</h1>');
  res.end();
}).listen(PORT, function () {
  console.log(`Server running on port ${PORT}`);
  
  // Open the server URL in the default browser
  open(`http://localhost:${PORT}`);
});

-1
投票

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


-1
投票

最好使用前端 JavaScript 框架,如 Angular、React 或 Vue 来路由到不同的页面。不过,如果你想在 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 非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.