Ionic 返回API响应而不是数据

jhiyze9q  于 2022-12-08  发布在  Ionic
关注(0)|答案(2)|浏览(209)

我一直盯着这个问题看了一段时间,最后意识到我的代码返回的是“200 ok.”响应,而不是实际的数据本身,这就是为什么它不会填充我的离子按钮。当我通过postman调用API,并将其打印到控制台时,它显示的是我需要的数据,所以我假设问题出在.ts文件的某个地方。
下面是我的API代码:

app.get('/getAllProvs', function (req,res) {
    //var id = req.params.id;

    connection.query('SELECT * from Patient', function(err, rows, fields) {
        if (!err){
            var response = [];

            if (rows.length != 0) {
                response.push({'result' : 'success', 'data' : rows});
            } else {
                response.push({'result' : 'error', 'msg' : 'No Results Found'});
            }

            res.setHeader('Content-Type', 'application/json');
            //res.status(200).send(JSON.stringify(rows));
            res.send(rows);
            console.log(rows);
        } else {
            res.status(400).send(err);
        }
    });
});

下面是我的供应商.ts代码:

export class RestService {

 data1: any;
  constructor(public http: Http) {
    console.log('Hello RestServiceProvider Provider');
  }

    getAllProvs(){
        if(this.data1){
            return Promise.resolve(this.data1);
        }
        return new Promise(resolve => {
            this.http.get('http://lndapp.wpi.edu:5000/getAllProvs')
            .map(res => res.json())
            .subscribe(data => {
                console.log("rest-services.ts subscribe");
                this.data1 = data;
                console.log(data);
                resolve(this.data1);
            });
        }); 

    }
}

下面是我的page.ts文件:

export class AllPatientsPage {
  data1: any;

  constructor(public app: App, public loadingCtrl: LoadingController, private toastCtrl: ToastController, public navCtrl: NavController, public restService: RestService){
    this.getAllProvs();
    }
  }
   getAllProvs(){
        this.restService.getAllProvs()
        .then(data => {
            console.log("all-patients.ts data");
            console.log(data);
            this.data1 = data;
        }).catch(e => {
            console.log(e);
        });
    }
}
vbkedwbf

vbkedwbf1#

从您的服务发送 json 响应:

res.json(rows);
vatpfxk5

vatpfxk52#

If this is happening during development, it could be because you're using the same url on your front end react website as your server.js site.
Example: front end running on : localhost:3000 backend listening on : localhost:3000/api
Fix: Change the port numbers.

  1. front end running on : localhost:3000
  2. backend listening on : localhost:5000/api
    Additional help:
  3. package.json: add proxy that points to your server: localhost:5000
  4. browser: clear your cookies.
    Hope this helps.

相关问题