ECONNFUSED在应用程序中进行GET请求时,API成功返回JSON

我正在用React编写节点应用程序,使用node-postgres和superagent进行后端调用。 比方说,我正在做一个GET请求,并使用返回的JSON来填充学生表。 我的API看起来像这样:

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

在页面加载时,这是从商店调用来设置学生数组。 这里似乎出现了一些问题:

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

如果我curllocalhost:3000/api/getStudents ,我得到我期望的JSON响应。

但是,当我在页面加载时调用这个,我得到一个ECONNREFUSED错误:

 Error: connect ECONNREFUSED 127.0.0.1:80] code: 'ECONNREFUSED', errno: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 80, response: undefined 

不知道为什么我在HTTP端口上收到错误。 这是我第一次使用node-postgres,superagent和React,所以任何帮助表示赞赏。

编辑:忘了提及,我能够做出POST请求,并插入项目没有任何错误的数据库。 这个错误只发生在我尝试GET请求时。

get方法中试试这个(插入完整的pathurl):

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

查看CORS的文档,了解使用绝对URL的例子:

https://visionmedia.github.io/superagent/#cors