I am new to mean stack , in fact working on my very first project , i want to remember the request from the specific browser , which i have done using cookies . After that i want to send the history data from the server specific to every request which i am not able to do , as i couldnt find a suitable way . i tried using sessionstorage in angular js but that doesnt pull the session data i kept in node js ) Please let me know how is make it .
Node js:
when i have set session var titles here in node js
var chkck = function(req,res,next){
console.log("inside cookie callback .. ");
req.session.titles = req.session.titles || [];
//titles.push(req.params.)
req.session.titles.push("22");
res.sendFile("F:/customer/public/index.html");
}
app.use(chkck);
app.get('/',function(req,res){
res.sendFile("F:/customer/public/index.html");});
angular js:
but in angular , i am not able to retrieve the titles from sessionstorage .
var nameapp=angular.module('name-App',["ngRoute",'ngCookies','ngStorage']);
nameapp.controller('NameCtrl',
function($scope,$http,$window, $cookieStore,$sessionStorage ){
$scope.arr=[];
$scope.finddet=function(){
console.log("sessionstorage.titles"+ $sessionStorage.titles);
}});
this gives undefined
In your Nodejs code: convert your response to JSON
res.send(JSON.stringify(data));
Sample answer
AnguarJs:
In your controller file,
$http.get(/your_url).then(function(response){
// You will get the above response here in response.data
})
Related
I have a React Native app that uses the dom-parser module to extract relevant pieces of information from a website, which is not owned by me. The information that I need is loaded dynamically in the page after it finishes loading in the browser. Is there a way to get this in a react native app using fetch()? I don't want the users to see the website open up in the app.
What I've tried:
const html = (await (await fetch(this.search_url)).text()); //get the document
var dom = parser.parseFromString(html); //parse it
var json = dom.getElementsByTagName("script")[5].innerHTML //this is the element that I need
console.log(json)
fetch(this.search_url).then((response)=>response.json()).then((json)=>{
var dom = parser.parseFromString(html);
var json = dom.getElementsByTagName("script")[5].innerHTML
console.log(json)
})
Both of these return a blank response as output. However, when I looked up the source of this.search_url in a browser, it is loading the data after a few seconds of loading the page. Is there a way to get this data in the app? Maybe some trick to make fetch() wait for a few seconds before writing the response?
I'am using express-session for creating session in nodejs & using http.post method to send datas to nodejs. How to retrieve the session variable in html using angularjs? Can you please help me?
Here is my code
Inside angularjs controller in the first html page,
$http.post('/form', data)
.then(
function(response){
if (response.data) {
$window.location.href = 'other.html';
}
},
function(response){
console.log("inside failure");
}
);
In nodejs,
app.post('/form', function (req, res) {
console.log("Incoming data" , userData);
req.session.mob = userData.mob;
req.session.provider = userData.provider;
res.send(req.session.mob);
}
I have to display the mob value in the 'other.html' which is stored in nodejs session.Can you suggest me how to do it through angularjs?
Not sure If i understand your question correctly - i'll try to help.
First of all, it will be angularJs best practice to use routes or states and pass the data you received from the server (response.data in your example) as a state param or a url param to the new page, and avoid the redirection.
If you do need to redirect to the "other.html" just pass the data from the server as query param in the url (if its a property) or save it in the browser storage (local storage, if the new page is being opened in a new tab) and read the data when your other.html is loaded.
Make sure that you pass a url to $window.location.href.
Basically what will happen is my angular page will make a post request to my express/node js application.
I want express on receiving that post request from angular to redirect to an other URL and also along with redirecting, want to POST data to that web page.
How will I use res.redirect("") in node js to also post some data.
Node js Code:
app.post('/ur-book',function(req,res){
var data=...;
res.redirect('/abcd');
});
I want to post data on /abcd and redirect to it.
other url will not be in my node app. It will be on a different website.
Simple way to do this is to create a function that handles request to /abcd and call that function from /ur-book like so
function handleAbcd(req, res) {
console.log(req.myData); // output will be undefined if it's not comming from /ur-book
res.json({});
}
app.post('/abcd',handleAbcd);
app.post('/ur-book',function(req,res){
// if you need to add some data you can add them to req.body or even your own for example req.myData
req.myData = 'hello';
handleAbcd(req, res);
});
I am storing authentication token in $rootScope . This token will be sent as part of header in every request via interceptor.
<code>
$rootScope.jwtToken=successfulResponse.data.body;
</code>
Interceptor code is as below :-
var bpInterceptor = function($q,$rootScope){
return {
request : function(config){
if($rootScope.jwtToken !== undefined){
config.headers.Authorization = $rootScope.jwtToken.token;
}
return config;
}
}
};
</code>
Q) Does $rootScope have different object for two browser sessions?
Angular code is executed client side only, so any state will disappear once you reload the page.
If you want to keep information between two user session, you have many options:
Keep that info in the URL using $location or location
Store that info in localStorage and retrieve it next time
Persist the information server side and query your server to get it back
Follow-up:
Once you get your token you can do:
localStorage.setItem('myToken', $rootScope.jwtToken);
And when you load your application, check if a token has been stored:
$rootScope.jwtToken = localStorage.getItem('myToken');
I am using Angular js to show loading screen. It works for all the REST services call except REST service to download the file. I understand why it is not working because for download I am not making any service call using $resource; instead of that I am using normal approach to download the file therefore Angular js code doesn't have any control on start/finish the service request. I tried to use $resource to hit this REST service however I am getting the data from this service and in this case loading screen was working fine however not sure how to use this data to display to user to download in angular way. Following are required details. Please help.
Approach 1 using iframe approach:
/*Download file */
scope.downloadFile = function (fileId) {
//Show loading screen. (Somehow it is not working)
scope.loadingProjectFiles=true;
var fileDownloadURL = "/api/files/" + fileId + "/download";
downloadURL(fileDownloadURL);
//Hide loading screen
scope.loadingProjectFiles=false;
};
var $idown; // Keep it outside of the function, so it's initialized once.
var downloadURL = function (url) {
if ($idown) {
$idown.attr('src', url);
} else {
$idown = $('<iframe>', { id: 'idown', src: url }).hide().appendTo('body');
}
};
Approach 2 using $resource (Not sure how to display data on screen to download)
/*Download file */
scope.downloadFile = function (fileId) {
//Show loading screen (Here loading screen works).
scope.loadingProjectFiles=true;
//File download object
var fileDownloadObj = new DownloadFile();
//Make server call to create new File
fileDownloadObj.$get({ fileid: fileid }, function (response) {
//Q? How to use the response data to display on UI as download popup
//Hide loading screen
scope.loadingProjectFiles=false;
});
};
This is the correct pattern with the $resource service:
scope.downloadFile = function (fileId) {
//Show loading screen (Here loading screen works).
scope.loadingProjectFiles=true;
var FileResource = $resource('/api/files/:idParam', {idParam:'#id'});
//Make server call to retrieve a file
var yourFile = FileResource.$get({ id: fileId }, function () {
//Now (inside this callback) the response data is loaded inside the yourFile variable
//I know it's an ugly pattern but that's what $resource is about...
DoSomethingWithYourFile(yourFile);
//Hide loading screen
scope.loadingProjectFiles=false;
});
};
I agree with you that this is a weird pattern and is different of other APIs where the downloaded data is assigned to a parameter in a callback function, hence your confusion.
Pay attention to the names and the cases of the parameters, and look that there're two mappings involved here, one between the caller to the $resource object and the object itself, and another between this object and the url that it contructs for downloading the actual data.
Here are some idea's for the second approach, you could present the user with a link after the download has happened:
With a "data url". Probably not a good idea for large files.
With a URL like "filesystem:mydownload.zip" You'd first have to save the file with the filesystem API. You can find some inspiration on html5rocks