提问者:小点点

使用html服务器运行Node.js应用程序


我目前正在学习Node.js开发,并尝试开始我的WebCode。我在Windows上使用Visual Studio代码。

当我用“npm start”启动应用程序时,“localhost:3000/”上的网站只是显示“服务器连接”。但是我如何看到所有其他文件,比如“index.html”呢?我必须在任何地方添加它们吗?

提前谢谢你。

null

Https Server File:

const http = require('http');

http.createServer(function(req, res){
    res.write('Server connect');
    res.end();
}).listen('3000');

null

null

package.json

{
  "name": "project-1",
  "version": "1.0.0",
  "description": "Project 1",
  "main": "index.html",
  "scripts": {
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "chartjs": "^0.3.24",
    "express": "^4.17.1",
    "http": "0.0.1-security",
    "mongodb": "^3.6.2",
    "mongoose": "^5.10.11",
    "nodemon": "^2.0.6"
  }
}

null


共2个答案

匿名用户

编写查看req的代码。该对象上的一个属性将告诉您正在请求的路径。(HTTP模块的API文档将告诉您这是什么属性)。

然后根据该路径决定要用什么来响应。

如果它是一个静态文件,那么从文件系统中读取那个静态文件,并在响应中输出它。

确保设置了正确的content-type标头。(如果您发送HTML,但说它是纯文本或JPEG图像(您说它是HTML),您会遇到问题。

你这是在重新发明轮子。您可能应该看看Express.js框架及其statice模块。

匿名用户

补充一下@Quentin说的话。下面是来自W3的一个很好的例子。

https://www.w3schools.com/nodejs/shownodejs.asp?filename=demo_ref_http

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World!');
  res.end();
}).listen(3000);

相关问题