ECONNREFUSED when executing a GET request in the application, but the API returns JSON successfully

I am writing a node application with React using node-postgres and a super agent for internal calls. Let's say I make a GET request and using JSON, it returns to populate the students table. 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); }); }); }); 

When loading the page, it is called from the repository to install an array of students. Something seems to be 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 been an error: getting students."); console.log(err); } else { return res; } }); } 

If I curl up localhost:3000/api/getStudents , I get the JSON response I expect.

However, when I call this to load the page, 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 

I don’t know why I get an error message on the HTTP port. This is my first time using node pegs, superspy, and React, so any help is appreciated.

Edit: Forgot to mention that I can make POST requests and insert items into the database without any errors. This error only occurs when trying to get a GET request.

+5
source share
1 answer

Try this (insert the full path URL) into the get method:

 request .get('http://localhost:3000/api/getStudents') .set('Accept', 'application/json') .end(function(err, res) { if (err) { console.log("There been an error: getting students."); console.log(err); } else { return res; } }); 

Check out the documentation for CORS for an example of using absolute URLs:

https://visionmedia.imtqy.com/superagent/#cors

+4
source

Source: https://habr.com/ru/post/1237620/


All Articles