leo0019 leo0019 - 2 months ago 9
Node.js Question

node server.js return nothing

I'm very new to Node. I just installed it via Brew and when I ran

node server.js
in the Terminal, the Terminal does nothing for hours.

node -v
v6.6.0


This is the server file, it is from a tutorial video that I'm watching. The point of this simple express server is to allow me the ability to quickly serve test data via HTTP to the front-end.

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 file :

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);


Thanks in advance

Answer

Try adding a console.log("started!") before app.listen. I'm guessing the server starts, but as is seen in your code, the only log it does is when it receives a request.

Try accessing http://localhost:6069/persons in your browser.

Edit: this defines a server response

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