Use socket in nodejs and angularjs - angularjs

I am new in socket.I have problem while using socket in my existing project.I have include socket.io.js file in my project and also create factory for using the socket. socket Request is going successfully from angular side.
I want to do when something is changed in my API response it automatically calls and show result in my page.So here is my code.I dont know how can i achieve this with socket
app.get('/ttms/getAlertsMessage/:customerid/:timstmp', getCookies, ttms.getAlertsMessage);// route
var socket = require('socket.io');
var io = socket.listen(server);
app.set('socketio', io);
io.on('connection', function (socket) {
console.log("==============connected=========")// this shows me connected
socket.on('test',function(data){
console.log(data)
})
});
Here is the node api which will call:
exports.getAlertsMessage = function(req, res, next) {
var customeruuid = req.param('customerid');
var start_time = new Date().getTime(),
request = require('request'),
api_url = global.common.base_url + 'ams/1.0.0/message/customeruuid/'+customeruuid;
var _m = new cLog.mObject('DELETE', 'deleteAllVNFBackup', api_url);
request({
url: api_url,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer " + req.cookies.apitoken
},
json: req.body
}, function(error, response, body) {
if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 202) {
res.end(JSON.stringify(body));
} else {
res.send(response.statusCode, {
"error": JSON.stringify(body)
});
});
}
Here is the angular service:
GetUserSettings.getAlertsMessage($scope.customerId).then(function(data) {
var data1={"test":"test"};
socket.emit('test', data1);
socket.on('result', function (data) {
console.log(data)// gives json {"test":"test"};
});
})
can anyone give me some idea how can i achieve this.

Related

AngularJS: Http header

I am newbie of angularJS. I want to add header in my http request but i am not understanding how? so far i've written this code.
Original code without header:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http.post(url, dataObj);
}
Now i am adding header to it, the code becomes like this:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http({headers: {
'Authorization': token
}}).post(url, dataObj);
}
By adding header, i am getting this error:
angular.js:14525 Error: [$http:badreq] Http request configuration url
must be a string or a $sce trusted object. Received: undefined
You're using the wrong syntax. Take a look at the angular documentation for $http here.
Your code should look like this:
$http({
method: 'POST',
url: __apiRoot + "/users/" + user.id,
data: JSON.stringify(user)
headers: {
'Authorization': token
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

server side data in angular

I am trying to make GET request with node request module. I am making request to the coursera api. As the api is using CORS. Therefore I have to make server side requests.
But the thing is how to use this data in index.html to dynamically fill data.
As here I am getting the whole data to the file. Is there any way to give this data to the Angular controller.
In brief, I want to use data from coursera api inside my angular app. I have used client side so know less about server side.
var request = require("request");
var fs = require("fs");
request("https://api.coursera.org/api/courses.v1").pipe(fs.createWriteStream("data.json"));
There are two ways you can get the data into index.html:
1) Use Jade (Pug) Render:
var COURSERA_DATA = null;
router.get('/', function (req, res) {
if (!COURSERA_DATA) {
request("https://api.coursera.org/api/courses.v1",function(err,res,body) {
COURSERA_DATA = body; /* verify first */
res.render('index', {data: COURSERA_DATA});
});
} else {
res.render('index', {data: COURSERA_DATA});
}
});
and then in index.html:
script(text/javascript).
var theDATA = !{JSON.stringify(data)}; // inserted by jade
and finally in angular1
app.controller('AnyController',function() {
var vm = this;
vm.data = theDATA;
});
2) Client request to URL which is proxied to coursera's API
router.get('/coursera', function (req, res) {
request("https://api.coursera.org/api/courses.v1").pipe(res);
}
Aaron
Why the problem to consume data right in Angular? Something like:
app.controller('controller', function($scope, $http) {
$scope.getCursera = function() {
$http({
url: "https://api.coursera.org/api/courses.v1",
method: "GET",
contentType: "application/json"
}).success(function(data) {
$scope.jsonResponse = data;
}).error(function(err) {
console.log(err);
});
};
});
If Coursera allow Cross Domain this it's works. The JSON response will be setted at the scope, such that you be able to show in view or do anything.
You can try to implement a simple api to send the response back to your controller like this..
In the server side .. (Demo)
var request = require('request');
router.get('/coursera', function (req, res,next) {
request.get(
'https://api.coursera.org/api/courses.v1',
{ json: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body); //response from coursera
// if you are using this as middleware write next()
}else {
res.send(new Error("Error while connecting to coursera"));
// if you are using this as middleware write next(err)
}
);
}
And in the angular controller ..
app.controller('controller', function($scope, $http) {
$scope.getCoursera = function() {
$http({
url: "baseURL/coursera",
method: "GET",
}).success(function(data) {
$scope.data = data;
}).error(function(err) {
console.log(err);
});
};
});

Unable send excel file data to web api

In my angular app , I am trying to upload an excel file to web api from Angular JS but I am unable to do so .
The method in the server web api is not being hit.
The angular code looks like :
$scope.file = null;
//UPLOAD FILE CODE
var formdata;
$scope.getTheFiles = function ($files) {
console.log($files[0].type);
formdata = new FormData();
angular.forEach($files, function (value, key) {
formdata.append(key, value);
});
};
// NOW UPLOAD THE FILES.
$scope.uploadFiles = function () {
var request = {
method: 'POST',
url: BasePath + 'uploadNative/UploadFiles/',
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
console.log(formdata);
if (formdata != null || formdata != undefined) {
$http(request)
.success(function (response) {
if (response != "Failed!") {
console.log("Succeeds");
}
else {
console.log("Failed");
}
})
.error(function () {
});
}
And the UI MVC controller which should invoke the web api controller causes exception.
public async Task<JsonResult> UploadFiles()
{
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
string url = BaseURL + "api/Upload/groupmembershipupload/";
string res = await Models.Resource.PostFileAsync(url, Token, hfc, ClientID);
var result = (new JavaScriptSerializer()).DeserializeObject(res);
return Json(result);
}
This PostFileAsync fires the exception.
using (client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthToken);
client.DefaultRequestHeaders.Add("ClientID", ClientID);
var content = new MultipartFormDataContent();
System.Web.HttpPostedFile hpf = data[0];
byte[] fileData = null;
using (var sds = new BinaryReader(hpf.InputStream))
{
fileData = sds.ReadBytes(hpf.ContentLength);
}
content.Add(new ByteArrayContent(fileData, 0, fileData.Count()));
//using (response = await client.PostAsJsonAsync(url + "?=" + DateTime.Now.Ticks, data))
using (response = await client.PostAsync(url + "?=" + DateTime.Now.Ticks, content))
{
...the response is Http Error 415 "Unsupported Media Type". It does not call the service.
Change the headers to:
headers: {
'Content-Type': 'multipart/form-data'
}

Nodejs post request

I am trying to login to a website with the following request:
var request = require('request');
var options = {
method: 'POST',
url: 'https://server/EnterpriseController',
params: {a: 1},
form: "actionType=authenticateUser&reqObj=[null,username,password,null,1]",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
withCredentials: true,
rejectUnauthorized: false
};
request(options,
function (error, response, body, data) {
if (request.method === 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var post = qs.parse(body);
});
}
console.log(body);
}
);
I am always getting an error. I think the form is wrong but I have the same login on an angularjs site without any error. I don't understand why the login works on angularjs site but not in nodejs.
)]}',
{"login_err": true, "resp": [null,null,null,1]
}
I missed the cookie:/ And the Formdata should be an Object.

How to return a success or fail code from Node.js to Angularjs

I am building my website with Angularjs and I am testing it with Node js and express. So, I am able to send a json item with information from the contact page form. But, I do not know How to return a success or fail code from Node.js to Angularjs to redirect to a thank you page. Also, I need to know how to send the information to my email and save it to a db and how to add a token for the form. I know that I'm using the MEAN stack. I learn better watch.
Here is my Node js:
var express = require('express');
var app = express();
var formidable = require('formidable');
app.use(express.static(__dirname + '/public')); // navigate to where the app reside
app.get('/', function (request, response) {
response.redirect('Index.html');
});
app.post('/Contact', function (request, response) {
var frm = new formidable.IncomingForm();
frm.parse(request, function(err, formData){
var Name = formData.Name,
Email= formData.Email,
Message = formData.Message;
response.writeHead(200, { "Content-Type": "application/json" });
response.end("{'status:' 200}");
});
});
var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);
and here is my Angularjs:
$scope.submit = function () {
console.log('Im in the controller');
console.log($scope.formData);
$http({
method : 'POST',
url : '/Contact',
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/json' }
}).success(function(result, status, headers, config) {
console.log(result);
if(result.status == "???"){
redirectTo: '/Thnkyu';
}
}).error(function(result, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(result);
});
}
When I submit the form; the console showed: TypeError: Cannot read property 'protocol' of undefined Before it showed: ERR_CONNECTION_REFUSED because I had the url portion before I setted the headers and data.
The problem was I use the angularJs $http dependence as shown above; but, it did not work. So, I use the $http dependence like so:
$scope.submit = function () {
console.log($scope.formData);
$http.post("/contact", $scope.formData)
.success(function(reponse){
if(reponse.status == 200)
console.log('im in')
$location.path('/thnkyu');
});
and the response from the server is like this:
...
if(!eor){
console.log(eor);
response.json({status: 200});
}

Resources