Node.js HTTP服务器无法启动,package.json解析错误求助
解决package.json解析错误及Node HTTP服务器搭建问题
错误原因:
package.json是JSON格式的配置文件,仅允许存放键值对形式的项目配置,不能写入Node.js执行代码。你错误地将服务器代码混入其中,破坏了JSON的结构规范,导致解析报错。修正后的package.json:
{ "name": "nodeserver", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
- 服务器代码的正确存放:在项目目录下创建
index.js文件(对应package.json中main字段指定的入口文件),将服务器代码写入该文件:
require("http").createServer((inRequest, inResponse) => { inResponse.end("Hello from my first Node Web server"); }).listen(80);
- 运行服务器:
- 打开终端,进入项目目录
C:\Users\USER\Desktop\nodeserver - 执行命令
node index.js - 打开浏览器访问
http://localhost,即可看到服务器返回的内容
- 打开终端,进入项目目录
内容的提问来源于stack exchange,提问作者Patrick Peyre
相关产品推荐
相关产品推荐

