0

我正在使用Node and Angualr JS组合express-4

在我的代码中,我试图newSourceId通过res.send. 我能够获得 newSourceId 但是当我使用它发送它时,res.send它会进入error而不是进入success.

我也尝试过使用res.sendStatus(newSourceId)但没有运气!

以下是 Node JS 部分:

app.post('/addObservationDetail',function(req,res){

var newSourceId = -1;

 Observation.create({obv_source:req.body.source,obv_waveband:req.body.waveband,prpsl_id:req.body.pId}
 ).then(function(result) {

        Observation.findAll({
            attributes: [['obv_id','id']],where:{prpsl_id:req.body.pId},order: [["obv_id","DESC"]],limit: 1
            }) .then(function(rows) {
                console.log("Obv_Id is = "+rows[0].dataValues.id);
                newSourceId=rows[0].dataValues.id;
                console.log("newsrc===="+newSourceId);
                 res.send(newSourceId);
            }); 
 });
});

这是 Angular JS 部分:

$scope.updateObsDet = function(obs_detail,index) {
            var url = "/";
            if(obs_detail.sourceId == null){
                url += "addObservationDetail";
                $http({
                    method:'POST',
                    url:url,
                    headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
                    transformRequest:function(obj){
                        var str = [];
                        for(var p in obj)
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        return str.join("&");
                    },
                    data:{source:obs_detail.source,waveband:obs_detail.waveband,pId:$scope.proposal.proposalId}                     
                }).success(function(data){
                    alert("New observation added");       //should come in here
                    updateSourceId(data,index,obs_detail);
                }).error(function(data){
                    alert(data);         //getting in here
                });

            } else {
                url += "updateObservationDetail";
                data = {
                        source:obs_detail.source,
                        waveband:obs_detail.waveband,
                        sourceId:obs_detail.sourceId
                        };
                $http.post(url,data).success(function(data){
                    alert(data);
                }).error(function(data){
                    alert(data);
                });
            }
        };

PS:我无法更改代码的角度部分,需要在Node JS部分进行更改。

4

1 回答 1

1

是的,你可以设置 json 响应试试这个

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ a: 1 }));
});
app.listen(3000);
于 2015-09-14T06:32:22.313 回答