简体   繁体   English

将JSON数据从angularjs发送到Node.js

[英]Sending JSON data from angularjs to nodejs

I having a problem in sending json data from front end angularjs to express nodejs. 我在从前端angularjs发送json数据以表达nodejs时遇到问题。 Here is what i have tried. 这是我尝试过的。

frontend.html page frontend.html页面

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

backend.js page 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 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");
});

I am not getting exact JSON in the node server part. 我在节点服务器部分没有得到确切的JSON。 This is what i am getting. 这就是我得到的。

output 产量

{ '{"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."}': '' } }

Can any one help, how can i get exact json in the node server part. 任何人都可以帮忙,我如何在节点服务器部分中获取确切的json。 So that i can parse and write only sentence field into a file. 这样我就可以解析并只将句子字段写入文件。

$http POST call, takes Object, not json.So you need to stringify your JSON before sending it to server. $ http POST调用使用对象而不是json,因此需要先将JSON字符串化后再发送到服务器。

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

Are you creating the post as JSON to send to node? 您是否以JSON形式创建帖子以发送到节点?

Angular will do this for you, you can put and object in the post as Ved suggests and Angular will magically change this to a JSON to send to the node server. 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");
 })
}

This will read on the server as: [Object object] as the bodyparser npm module in node will change it back to an Object 这将在服务器上读取为: [Object object]因为节点中的bodyparser npm模块会将其更改回Object

Try to set the datatype to json before send to the server. 在发送到服务器之前,尝试将数据类型设置为json。 It will set the Content-Type header to application/json which the server can understand as a 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) {

})

Update: I tried to run your source code and modify a little bit, you can check if it response the right format that you want. 更新:我试图运行您的源代码并进行一些修改,您可以检查它是否响应所需的正确格式。 Checkout this repo: https://github.com/nguyennb9/sample-angularjs-expressjs 签出此仓库: https : //github.com/nguyennb9/sample-angularjs-expressjs

Use application/json in header while POST method POST方法时在标头中使用application / json

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

  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM