node.js - Node server.js 不返回任何内容

标签 node.js terminal nodes node-modules

我对 Node 还很陌生。我刚刚通过 Brew 安装了它,当我在终端中运行 node server.js 时,终端在几个小时内什么也不做。

 node -v
 v6.6.0

这是服务器文件,来 self 正在观看的教程视频。这个简单的 Express 服务器的目的是让我能够通过 HTTP 向前端快速提供测试数据。

package.json:

{
    "name": "simple-server",
    "version": "1.0.0",
    "description": "",
    "main": "server.js",
    "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node server.js"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "body-parser": "^1.14.1",
        "express": "^4.13.3",
        "path": "^0.12.7"
    }
}

server.js 文件:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();

//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type,     Accept");
  res.header("Access-Control-Allow-Methods", "POST, GET");
  next();
});

app.use(express.static(path.join(__dirname + '/public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

var persons = [
    "person1.jpg",
    "person2.jpg",
    "person3.jpg",
    "person4.jpg",
    "person5.jpg",
    "person6.png"
];

app.get('/persons', function(req, res) {
    console.log("GET From SERVER");
    res.send(persons);
});

app.listen(6069);

提前致谢

最佳答案

尝试在 app.listen 之前添加 console.log("started!")。我猜服务器会启动,但正如您的代码中所见,它执行的唯一日志是当它收到请求时。

尝试在浏览器中访问http://localhost:6069/persons

编辑:这定义了服务器响应

app.get('/persons', function(req, res) { 
   console.log("GET From SERVER");
   res.send(persons); <-- server sends persons array to client
});

关于node.js - Node server.js 不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39681135/

相关文章:

c - 在一个 block 中定义和声明结构与声明然后定义结构之间是否存在明显差异?

kubernetes - 为什么内存使用量比我在 Kubernetes 的节点中设置的要大?

node.js - NPM 安装错误(Angular 6)

javascript - 将 Javascript If 语句构造为在函数中同步的最佳方法

javascript - npm 登录 - 注册表为 PUT 返回 401

linux - 不使用鼠标在终端中选择文本

python - 如何从 Python 脚本在终端中执行命令?

mysql - Nodejs Sequelize 和passport Js,在注册用户时卡在执行查询上

bash - 通过命令重定向终端标准输出

java - 在 Neo4j 索引中创建第 128 个节点后,无法访问更多节点