繁体   English   中英

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

[英]Running Node.js Application with html server

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

当我使用“npm start”启动应用程序时,“localhost:3000/”上的网站只显示“Server Connect”。 但是我如何查看所有其他文件,如“Index.html”? 我必须在任何地方添加它们吗?

先感谢您。

 Https Server File: const http = require('http'); http.createServer(function(req, res){ res.write('Server connect'); res.end(); }).listen('3000');

 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" } }

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

然后根据该路径决定您想要响应的内容。

如果它是一个静态文件,则从文件系统中读取该静态文件并将其输出到响应中。

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


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

添加@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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM