Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular post json to express

I'm trying to send a json to a server node/express with angular.js

my 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);

My 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');
});
}

When my server is receiving a POST, I use:

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

to capture the route ?

My angular app is ok?

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);
        })
};
  });

the error: Cannot POST /[object%20Object] has something wrong with my post,
it will send: [object% 20Object]

like image 639
Mateus Vahl Avatar asked Feb 14 '23 08:02

Mateus Vahl


1 Answers

Try to change to this:

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

Looks like you use incorrect $http.post method signature. It should be:

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

... and since success and error methods are deprecated, it should better be

$http.post('http://localhost/post/', dados)
.then(function() {...})   // success
.catch(function() {...}); // error
like image 81
dfsq Avatar answered Feb 17 '23 21:02

dfsq