beNerd
beNerd

Reputation: 3374

express.js app throws no response

Here is a express server code:

var express = require('express');
var mysql = require('mysql');
var app = express();

app.use(express.bodyParser());
app.use(express.static('public'));
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'someuser',
  password : 'somepassword',
  database: 'some_database'
});

connection.connect();
app.get('/users/authenticate', function(req, res){
res.setHeader('Content-Type', 'application/json');
res.send({test:"test"});
res.end();

});

app.listen(3000);
console.log('Listening on port 3000');

Now when i issue a get request to this API, i get nothing in response tab of network console though response code is 200 ok. Please shed some light. I expect JSON data here. Here is what i get in my console:

enter image description here

enter image description here

Upvotes: 1

Views: 4518

Answers (2)

Brian Lewis
Brian Lewis

Reputation: 5729

Try using:

app.get('/users/authenticate', function(req, res){
    res.json({foo:'bar'});
});

Also, if you are doing this across different domains, you will need to setup CORS.

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

app.configure(function() {
    app.use(allowCrossDomain);
}

...and if you are attempting to test CORS from a localhost, you will need to open Chrome with some security disabled. If you are on a Mac, it is done with the following command. Just make sure Chrome is closed before you run it.

`open -a Google\ Chrome --args --disable-web-security`

Upvotes: 1

az7ar
az7ar

Reputation: 5237

The code is ok. I am getting {test:"test"} both from browser and also using

curl http://localhost:3000/users/authenticate

Upvotes: 0

Related Questions