簡體   English   中英

Express / Node.js中的HTTP請求

[英]HTTP request from within Express/Node.js

我正在嘗試為正在編寫的程序建立快速服務,該程序與外部API聯系,然后返回結果,以便可以將其存儲在已設置的Mongo中。

這似乎應該很簡單,但是我是Node.js / Express的新手,並且收到“無法在發送標頭后設置標頭”錯誤。

我從外部API獲取所需的數據,但是如何將這些數據正確發送回Angular app.js,以便可以在表中更新?

“ addSelected()”是我在app.js中調用以啟動該過程的函數。 “數據”會在整個響應過程中進行部分打印,但會中斷並顯示“發送后無法設置標題”錯誤。 據我了解,這是從發送響應,然后在事實發生后嘗試修改響應標頭開始的。.但是我不確定是否有解決方法,或者我是否格式化所有錯誤,因為這是我在MEAN堆棧中的第一次嘗試一般。

我知道問題出在server.js中的“ res.send(data)”行上,但我不知道如何正確格式化響應。

我的代碼:

server.js

//server.js


//setup ==============================
var express = require ('express');
var request = require('request');
var app = express();
var mongoose = require('mongoose');
var https = require('https');

//config ============================
app.use(express.static(__dirname + '/public/'));

console.log("running PipeHelper");

mongoose.connect('mongoedit');
var Schema = mongoose.Schema;
var opSchema = new Schema({

        title: String,
        description: String,
        company: String,
        post_date: String,
        close_date: String,
        contact: String,
        location: String,
        url: String,
        notice_type: String
    });

var item = mongoose.model('item', opSchema);



//routes===========================

//returns full database
app.get('/api/db', function(req, res){

    item.find({},function(err, items){

        if (err) res.send(err);
        res.json(items);
    });

});


//searches FBO for opportunities to add to database
app.get('/api/search:FBO_key', function(req, res){


    var data;
    console.log("2");
    var baseURL = "api.data.gov"
    var params = "/gsa/fbopen/v0/opps?q=" + req.params.FBO_key;
    params += "&api_key="+"keyyyy";
    params += "&all";
    params += "&start=0";
    params += "&p=1";
    params += "&limit=10";
    url = baseURL+params;

    var options = {
        port: 443,
        host: 'api.data.gov',
        path: params,
        method: 'GET'


    };

    //get FBO data
    var request = https.request(options, function(response){
        console.log("4");
        response.on('data', function (chunk){

            //response data to send back to app.js
            data += chunk.toString();
            res.send(data);


        });


    });

    console.log("3");
    request.end();


    request.on('error', function(e){
        console.error(e);
    });


});

app.get('/', function(req,res){

    res.sendfile('./public/index.html');

});

app.listen(8000);

app.js

var app = angular.module("pipeHelper", ['smart-table']);

app.controller('mainCtrl', [
'$scope', '$http', function($scope, $http){

$scope.selected = [];
$scope.displayData= [];
$scope.items=[];
$scope.FBOsearch;



//populates table on startup with whole DB
$http.get('./api/db')
    .success(function(data){
        $scope.items=data;
        $scope.displayData = [].concat($scope.items);

    })
    .error(function(data){
        console.log('Error: '+data);
    });



$scope.addSelected = function(){

    //search FBO, add opportunities, update table
    console.log("1");


    $http.get('./api/search'+'NGA')
    .success(function(data){
        console.log("5");
        console.log(data);
        $scope.items=data;
        $scope.displayData= [].concat($scope.items);

    })
    .error(function(data){

        console.log('Error: ' +data);

    });

};




$scope.isSelected = function(item){
    //if its selected, remove it
    // if its unselected, add it
    if ($scope.selected.indexOf(item)==-1){
        $scope.selected.push(item);
    }
    else{

        $scope.selected.splice($scope.selected.indexOf(item), 1);
    }



    console.log($scope.selected);
    //temp placeholder function.  Eventually add to array of selected objects for placement in Pipeliner/deletion

};







}]);

解決了這個問題。 我沒有意識到response.on('data')被多次調用,因此多次調用了res.send(data)並導致錯誤導致崩潰。 我在請求函數中添加了以下內容:

response.on('end'function(){
    res.send(data);
};

基本上在外部API數據輸入完畢后,用express進行發送。 我想通過做中學。 希望這最終能對某人有所幫助。

我不能發表評論,所以我將其作為答案。

我建議安裝node-inspectornpm install -g node-debug 然后使用node-debug server.js運行您的應用程序。 這將產生Firefox或Chrome開發工具的新實例,並允許您調試nodeJS代碼。 很有用。

如果我猜的話,您看到的錯誤很可能與request.end()有關。 調用.end()之后,您將無法再修改標頭內容。 我懷疑這會有所不同,但是請在調用request.on('error')之后嘗試放入request.end()

編輯:10/15/15

我強烈建議安裝VS Code 它具有用於節點應用程序的內置調試器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM