I'm writing a node app with React, using node-postgres and superagent for backend calls. Let's say I'm making a GET request and using the JSON it returns to fill a table of students. My API looks like this:
import pg from 'pg';
import Router from 'express';
let router = new Router();
let conString = "postgres://user:pass@localhost/db_name";
router.get('/getStudents', function(req, res) {
var results = [];
pg.connect(conString, function(err, client, done) {
if (err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}
var query = client.query('SELECT first_name, last_name, email FROM students');
query.on('row', function(row) {
results.push(row);
});
query.on('end', function() {
done();
return res.json(results);
});
});
});
On page load, this is called from the store to set a students array. It seems like something is going wrong here:
var request = require('super agent');
function getStudents() {
request
.get('/api/getStudents')
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) {
console.log("There's been an error: getting students.");
console.log(err);
} else {
return res;
}
});
}
If I curl localhost:3000/api/getStudents
, I get the JSON response I expect.
However, when I call this on page load, I get an ECONNREFUSED error:
Error: connect ECONNREFUSED 127.0.0.1:80]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 80,
response: undefined
Not sure why I'm getting an error on the HTTP port. This is my first time using node-postgres, superagent, and React so any help is appreciated.
Edit: Forgot to mention that I'm able to make POST requests and insert items into the database without any errors. This error only occurs when I'm attempting a GET request.
Try this (inserting the full path url) in the get
method:
request
.get('http://localhost:3000/api/getStudents')
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) {
console.log("There's been an error: getting students.");
console.log(err);
} else {
return res;
}
});
Check out the documentation for CORS for an example of using absolute urls: