2013-12-19 38 views
4

我想一個JSON發送到服務器節點/與angular.js角度支柱JSON表達

表達我server.js

/* 
* Setup 
*/ 
// Dependencies 
var express = require('express'); 
// Start Express 
var app = express(); 
// Conf port 
var port = process.env.PORT || 3000; 
/* 
* Conf. the app 
*/ 
    app.configure(function() { 
     app.use(express.static(__dirname + '/public')); 
     app.use(express.logger('dev')); 
     app.use(express.bodyParser()); 
     app.use(express.methodOverride()); 
    }); 

/* 
* Routes 
*/ 
require('./app/routes')(app); 

/* 
* Listen 
*/ 
app.listen(port); 
console.log("App listening on port " + port); 

我Routes.js

module.exports = function (app) { 

app.post('/post/:name', function (req, res) { 
    console.log("Serv get [OK]"); 
    /* 
    * Disparar broadcast para all 
    */ 
}); 
app.get('/', function (req, res) { 
    res.sendfile('./public/view/index.html'); 
}); 
} 

當我的服務器正在接收POST時,我使用:

app.post('/post'... 
    OR 
app.get('/get'... 

捕捉路線?

我的角度應用程序可以嗎?

webchatApp = angular.module("webchatApp",[]); 

webchatApp.controller('webchatCtrl', function ($scope,$http) { 
$scope.sendMsg = function() { 
    var dados = {name:"test message"}; 
    $http.post({url:'http://localhost/post/',data:dados}) 
     .success(function (data) { 
      console.log("Success" + data); 
     }) 
     .error(function(data) { 
      console.log("Erro: "+data); 
     }) 
}; 
    }); 

錯誤:Cannot POST /[object%20Object] 有我的帖子,
東西錯了,它就會發出:[對象%20Object]

回答

7

試圖改變這樣的:

$http({ 
    method: 'POST', 
    url: 'http://localhost/post/', 
    data: dados 
}) 
.success(function() {}) 
.error(function() {}); 

看起來像您使用不正確的$http.post方法簽名。它應該是:

$http.post('http://localhost/post/', dados) 
.success(...) 
.error(...); 

...既然successerror方法已過時,它最好是

$http.post('http://localhost/post/', dados) 
.then(function() {...}) // success 
.catch(function() {...}); // error 
+0

這個作品,我試圖以錯誤的方式使用POST, T.您 –

+1

.success()和.error()現在已棄用。使用.then()代替。 https://docs.angularjs.org/api/ng/service/$http – Darcy