小编joh*_*sco的帖子

在应用程序中发出GET请求时ECONNREFUSED,但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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

在页面加载时,从商店调用此项来设置学生数组.这似乎出现了问题:

var request = require('super agent');

function getStudents() {
   request
     .get('/api/getStudents')
     .set('Accept', 'application/json')
     .end(function(err, res) …
Run Code Online (Sandbox Code Playgroud)

json node.js superagent node-postgres reactjs

10
推荐指数
1
解决办法
2万
查看次数

标签 统计

json ×1

node-postgres ×1

node.js ×1

reactjs ×1

superagent ×1