【问题标题】:Sending JSON data from angularjs to nodejs将 JSON 数据从 angularjs 发送到 nodejs
【发布时间】:2016-12-14 18:26:08
【问题描述】:

我在从前端 angularjs 发送 json 数据以表达 nodejs 时遇到问题。这是我尝试过的。

frontend.html 页面

<form ng-submit="func()">
    <textarea name="inputtext" type="text" ng-model="sentence"></textarea>
</form>

backend.js 页面

$scope.func = function(){

 $scope.jsondata = {"status":"OK","language":"english","sentences":[{"sentence":"That's a nice restaurant."},{"sentence":"Also I went to another bad restaurant."},{"sentence":"I didn't like that movie."}]}

 $http.post('/sample',$scope.jsondata).success(function(data,status){
        console.log("Success");
     })
}

server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');

app.set('views', __dirname + '/views');
app.set('view engine' , 'ejs');

app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });

app.use(express.static('public'));

app.get('/',function(req,res){
    res.render('index',{ title: 'Sentence' });
});
app.post('/sample',urlencodedParser,function(req,res){
    console.log(req.body);
});
http.listen(8888, function(){
   console.log("Server listening on 8888");
});

我在节点服务器部分没有得到准确的 JSON。这就是我得到的。

输出

{ '{"status":"OK","language":"english","sentences":': { '{"sentence":"That\'s a nice restaurant."},{"sentence":"Also I went to another bad restaurant."},{"sentence":"I didn\'t like that movie."},{"sentence":"Thats a very bad movie."}': '' } }

任何人都可以帮忙,我怎样才能在节点服务器部分获得准确的 json。这样我就可以只解析句子字段并将其写入文件。

【问题讨论】:

    标签: javascript angularjs json node.js express


    【解决方案1】:

    $http POST 调用,接受 Object,而不是 json。因此,您需要在将 JSON 发送到服务器之前对其进行字符串化。

    $http.post('/sample',JSON.stringify($scope.jsondata)).success(function(data,status){
            console.log("Success");
         })
    }
    

    【讨论】:

    • 您好,感谢您的回复。我试过 JSON.stringify($scope.jsondata) 。但我仍然得到相同的输出。在服务器端我无法解析。
    • 还有任何其他方法,这样我们就可以解析 JSON 并将句子字段写入文件,仅在 angularjs 端。
    【解决方案2】:

    您是否将帖子创建为 JSON 以发送到节点?

    Angular 会为您执行此操作,您可以按照 Ved 的建议在帖子中放置和反对,Angular 会神奇地将其更改为 JSON 以发送到节点服务器。

    $scope.func = function(){
    
    $scope.data = {language:"english", sentences:   [{sentence:"That's a nice restaurant."},{sentence:"Also I went to another bad restaurant."},    {"sentence":"I didn't like that movie."}]}
    
    $http.post('/sample',$scope.data).success(function(data,status){
        console.log("Success");
     })
    }
    

    这将在服务器上读取为:[Object object],因为 node 中的 bodyparser npm 模块会将其更改回 Object

    【讨论】:

      【解决方案3】:

      在发送到服务器之前尝试将数据类型设置为 json。它将 Content-Type 标头设置为application/json,服务器可以将其理解为 json

      $http({
          method: 'POST',
          url: baseUrl + '/sample',
          dataType: "json",
          data: {
              "status": "OK",
              "language": "english",
              "sentences": [{"sentence": "That's a nice restaurant."},
                  {"sentence": "Also I went to another bad restaurant."},
                  {"sentence": "I didn't like that movie."}]
          }
      }).success(function (data, status) {
      
      }).error(function (data, status) {
      
      })
      

      更新: 我尝试运行您的源代码并稍作修改,您可以检查它是否响应了您想要的正确格式。查看此仓库:https://github.com/nguyennb9/sample-angularjs-expressjs

      【讨论】:

      • 您好,感谢您的回复。输出没有变化。它仍然以这种格式出现:{ '{"status":"OK","language":"english","sentences":': { '{"sentence":"That\'s a nice restaurant."},{"sentence":"Also I went to another bad restaurant."},{"sentence":"I didn\'t like that movie."},{"sentence":"Thats a very bad movie."}': '' } }
      【解决方案4】:

      使用 application/json 在标头中使用 POST 方法

       $http({
          method:'POST',
          dataType: "json",
          url: 'http://localhost:8000/saveform',
          data : $scope.user, 
          headers: {
            'Content-Type': 'application/json' 
          }
        }).success(function(data){
      
        });
      

      【讨论】:

        猜你喜欢
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 2014-08-24
        • 1970-01-01
        • 1970-01-01
        • 2016-09-02
        • 2012-05-18
        • 2016-10-25
        相关资源
        最近更新 更多