So I am trying to send some data I have in angular to my nodejs server. Let me start with my code: index.html
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
</ion-content>
</ion-pane>
<div ng-controller="myCtrl">
<form>
<input type="text" ng-model="message">
<input type="submit" value="Submit" ng-click="submit()">
</form>
</div>
</body>
Here is a text box with data, then the submit button will send the message and deviceID to the server.
app.js
var app = angular.module('starter', []);
app.controller('myCtrl', function($scope, $http) {
var devToken;
var push = new Ionic.Push({
"debug": true
});
push.register(function(token) {
devToken = token;
console.log("Device token:", token.token);
});
$scope.submit = function() {
var message = "Hello";
$http({
method: 'POST',
url: 'http://127.0.0.1:8080',
token: devToken,
message: message
})
}
})
As you can see, I am trying to grab a message and the deviceID and post it to my express server.
server.js
var express = require('express');
var bodyParser = require('body-parser');
var apns = require('apns');
var gcm = require('node-gcm');
var app = express();
var sender = new gcm.Sender('AIzaS.........plD2s8');
var registrationTokens = [];
registrationTokens.push('Insert Device ID here that is passed from app.js');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', function(req, res) {
console.log("DEVICE ID == " + req.body.devToken);
sender.send("Hello", { registrationTokens: registrationTokens });
})
app.listen(8080, function() {
console.log('running on port 8080');
});
SO to recap, I am needing help getting my data when submitted to be available on my nodejs express server (which runs at a different domain/port than the Angular app). Can anyone help me figure out how to get my data from angular to express nodejs? Any help is appreciated.
thanks
You need to create a route to capture the post:
app.post('/', function(req, res) {
console.log(req.body);
...
});
Then the front end could pass whatever you want
$http.post("/", {message:message, devToken:devToken}).success(function(message, status) {
console.log('Message posted');
})
If the backend is not on the same origin as the OP states in the comments, you would need to enable cross origin requests.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Note: don't use * for production unless really want to allow requests from anywhere.