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

时间:2015-04-23 06:16:13

标签: html node.js url browser server

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

server.js文件如下所示:

> head(file2)
  Sl.No. Commodity.Name
1      1         Diesel
2      2         Pancil
3      3   Pencil-HB 02
4      4  Pencil-Apsara
5      5 Pancil-Nataraj
6      6     Pen-Parker
> 
> CName <- levels(file1$Commodity.Name)
> CName.lower <- tolower(CName)
> correct_1 <- function(x){
+     scores = stringdistmatrix(tolower(x), CName.lower, weight=c(1,0.001,1,0.5))
+     if (min(scores)>2) {
+         return(x)
+     } else {
+         return(as.character(CName[which.min(scores)]))
+     }
+ }
> correct <- function(x) {
+     sapply(as.character(x), correct_1)
+ }
> 
> correctedfile2 <- file2 %>%
+ transmute(Commodity.Name.Old = Commodity.Name, Commodity.Name = correct(Commodity.Name))
> 
> file1$Commodity.Name = as.character(file1$Commodity.Name)
> correctedfile2 %>%
+ left_join(file1[,-1], by="Commodity.Name")
  Commodity.Name.Old Commodity.Name Commodity.Category
1             Diesel         Diesel               <NA>
2             Pancil         Pencil         Stationary
3       Pencil-HB 02         Pencil         Stationary
4      Pencil-Apsara         Pencil         Stationary
5     Pancil-Nataraj         Pencil         Stationary
6         Pen-Parker            Pen         Stationary
7       Pen-Reynolds            Pen         Stationary
8     Monitor-X001RL        Monitor           Hardware

我在浏览器中使用此URL来触发&#34; hello world&#34;响应:

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

我希望能够在传递这样的网址时打开一个基本的html页面:

http://localhost:8080/

我查看了许多教程和一些stackoverflow帖子,但是这个特定任务的内容并不多。有没有人知道如何通过对server.js文件的简单修改来实现这一目标?

2 个答案:

答案 0 :(得分:0)

如果您希望在&#34; http://localhost:8080/test.html&#34;的帮助下通过nodejs打开.html文件。这样的url,你需要将.html页面转换为.jade格式。在expressjs framework.Express渲染引擎的帮助下使用渲染引擎将帮助你在nodejs服务器上渲染.jade文件。

答案 1 :(得分:0)

最好使用诸如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非常有用。