Race condition when fetching request.url in Node / Express - javascript

I have a Node webapp which supports URLs in multiple languages. I have some middleware to generate a Welsh version of the current URL (eg. for the URL /foo, the Welsh version would be /welsh/foo), which is presented on-page as a link.
This function takes a request object and returns the updated URL (accessed via request.url). Unfortunately, when I open several pages at once on my site, some pages get the wrong URL in the <a> link (eg. they get the Welsh URL for one of the other pages I've opened). If I reload the page, the link is re-generated, this time correctly.
My middleware looks like this:
res.locals.getCurrentUrl = (req, locale) => {
// snip: some logic to check if the URL already contains the locale
return "://" + req.get('host') + req.originalUrl;
};
... then I call it in templates like getCurrentUrl(request, 'welsh').
I only see this behaviour when I open a dozen tabs at once (via JavaScript – I have a status page with a button that opens a bunch of site URLs at once). Obviously this isn't a real-life use case, but at moments of high traffic, this race condition might kick in.
Is there a better, more reliable way here to associate per-request variables like url with the rendered output? Am I doing something wrong?

Fixed this by making the request object available to my templates in a middleware function (beforehand I set it as a global on the template engine which clearly introduced this race condition):
app.use(path, (req, res, next) => {
res.locals.request = req;
return next();
});

It might be that you're using a Lambda function, and those retain the outer scope.
Try
res.locals.getCurrentUrl = function() {...}
instead.

Related

RingCentral JavaScript SDK Handle Redirect URI points to local JavaScript Function

RingCentral JavaScript SDK handle redirect URI point to local JavaScript function
As-per Doc, they give option
RingCentral.SDK.handleLoginRedirect()
but dont know how to use that
var SDK = require('ringcentral');
rcsdk = new SDK({
server: SDK.server.sandbox,
appKey: '_app_key',
appSecret: 'app_password',
redirectUri: ''
})
function handleredirectURI(){
//handle redirections
}
We need points out our handleredirectURI function
Thanks in advance
Per the documentation. The context is 3-legged oAuth. Here is a demo: https://github.com/ringcentral/ringcentral-demos-oauth/tree/master/javascript
However the demo doesn't use the handleredirectURI method. Which means that the method is simply an utility method and it's not required to use it.
For the usage of handleredirectURI, I will come back and update my answer later.
Update
Here is the source code for handleredirectURI: https://github.com/ringcentral/ringcentral-js/blob/669b7d06254d3620c5a5f24c94b401aa862be948/src/SDK.js#L115-L124
You can see that the method parses win.location to get some useful data and postMessage back to its opener.
Unit tests for handleredirectURI: https://github.com/ringcentral/ringcentral-js/blob/669b7d06254d3620c5a5f24c94b401aa862be948/src/SDK-spec.js#L27-L63
Update 2
I read handleredirectURI' source code, unit tests, sample code again and I think its usage is just like what is written in its documentation:
Popup Setup
This setup is good when your app is rendered as a widget on a third-party sites.
If you would like to simply open RingCentral login pages in a popup, you may use the following short-hand in your app's login page:
var platform = rcsdk.platform();
var loginUrl = platform.loginUrl({implicit: true}); // implicit parameter is optional, default false
platform
.loginWindow({url: loginUrl}) // this method also allows to supply more options to control window position
.then(function (loginOptions){
return platform.login(loginOptions);
})
.then(...)
.catch(...);
In this case your landing page (the one to which Redirect URI points) need to call the following code:
RingCentral.SDK.handleLoginRedirect();
Explained:
Run the first code snippet to open the login popup.
In the redirected to page, run the second code snippet (that one line of code) to get everything else done.
After that the authorization part is done and you can invoke other APIs.
Let me know if you have more questions.

AngularJs bookmarkable url and query parameters

I'm trying to fix one mistake which one of the previous developer has did. Currently in project we have half-bookmarkable pages. Why half? Because if token has expired user will be redirect to resourse where he has to provide his credentials and on success he will be redirect to previous resource which he has used before. Sounds good for now. The problem here is next, some of resources have server side filtering and highly complicated logic which comes in the end to the one object like this:
param = {
limit: 10,
offset: 0,
orderBy: 'value',
query: 'string query can include 10 more filters'
};
then thru the service it sends a request to the end point
var custom = {};
function data(param) {
custom.params = param;
return $http.get('/data_endpoint', custom)
.then(function (response) {
return response.data;
});
From this part request works fine and response is correct but url isn't. User cannot store current url with search params because url doesn't have it and if user will try to get back to previous page with applied filters he won't be able to do that.
Also there is interceptor in this application, which add one more query param to every api request, because every api request requires some specific validation. This param is always the same.
I have tried to add $location.search(param) exactly to this data service but it breaks the app with infinity loop of login / logout looping, because interceptor stops working and all other request are sending without special query param
Then I thought to add this params inside interceptor like this:
config.params.hasOwnProperty('query') ? $location.search(config.params) : $location.search();
But it still breaks app to infinity loop.
This method adds query to url but doesn't allow to modify it, so if user applied additional filtering, it doesn't send new modified request but sends old one.
if (config.params.hasOwnProperty('query')){
for (var key in config.params){
$location.search(key, config.params[key])
}
}
That's why I decided to ask question here, probably somebody gives an advice how to solve this problem. Thanks in advance.

Node JS sending data via URL

Recently i started programming with Node JS and found it an amazing replacement for php . In php i used to send get requests with Data in the url .
Something like : http://sample.com/public.php?x=helloworld
How to perform something like this in Node JS or is there a better way to send data to node unlike using the url in the above case .
Also , I have noticed that in some cases like stackoverflow , queries are different and dont include the file name
like /public?= instead of /public.php?=
How is this achieved , i always thought this was something related to REST . Also , if you have the answer you might as well guide me if it could be done with Node and a few sources to learn could be of help too .
the most regular way to use REST api
req.query
// GET /search?q=foo+bar
req.query.q
// => "foo bar"
// GET /phone?order=desc&phone[color]=black&shoe[type]=apple
req.query.order
// => "desc"
req.query.phone.color
// => "black"
req.params
// GET /user/william
req.params.name
// => "william"
req.body(for form data)
// POST /login
req.body.username
// => "william"
req.body.password
// => "xxxxxx"
You'll probably be much better off using a pre-existing module as your web server. You can set one up manually, but you have to know about a lot of potential edge cases and really understand web servers. Most people in node use express. In node, as in any server-side language, you can pass data around in a few ways. The query string is one. You can also put some parameters directly in the url (like "/users/12" where 12 is a user id). Depending on the type of request, you can put data in the body of the request. You can also pass cookies. These are not node-specific. Explaining how express works in a post like this would be crazy, so I'll just give you a short example of a what a route handler matching your example route might look like:
var express = require('express');
var app = express();
app.get('/public', function(req, res, next) {
// Get the value from the query string. Express makes the query
// available as an object on the request parameter.
var x = req.query.x;
// Execute your main logic
doSomethingWithX(x);
// Send a response
res.status(200).json({ foo: 'bar' });
});

Angularjs: maintain http body after redirect

Hi everybody and sorry for the English (if you found some mistakes),
I have the next question: I am in the page A and I call a web service that returns a JSON in the body, after this I redirect to another page B.
My question: after the redirection, body is kept ? In oder words, can I get or access to the body (if the body contains the JSON)?
Example
The web service:
app.service('LoginService', ['$http', function($http) {
this.retrieveUser = function(username, password) {
var url = app.baseURI + username+"/"+password;
return $http.get(url);
};
...
JS redirect
self.login = function(username, password){
LoginService.retrieveUser(username, password)
.success(function (data) {
if(data.usuario.rol == "G")
window.location.href="http://localhost:8080/Natureadventure/html/gerente/gestionarActividades.html";
}).error(function(data){
$scope.loginForm.password.$setValidity("password", false);
});
};
Thanks!
Angular is completely client-sided, so, aside from setting something in localStorage, cookies or sessionStorage, no, you will not be able to do this.
The way around it is to turn your Angular application into a single-page application; you never really change the page of the website as such, but Angular can emulate the changing of your web page (i.e the content and the layout) through a library like ui-router or ngRoute.
The downside to this is that if you are either stuck with ugly hashbang URLs or you enable html5Mode, which breaks if you refresh the page. The way to fix that is to either a) stick with hashbang URLs or b) make your server redirect any unknown request to your index.html and let angular do the routing for you.

How do I generate a unique link that will load a session with certain docs available to the client?

Sorry for the bad phrasing.
Essentially, I want to be able to generate a link to a page, which will load a session of certain docs.
For example, Links.find() returns to Client A Links.find({clientName:"A"}). Now Client A wants to send this series of elements to his friend, and wants to do so by sending him a link which loads a client instance that can see Links.find({clientName"A"}).
Any input at all would be greatly appreciated.
Add Iron Router to your project. Then create a route that puts the relevant query into the URL, for example (in a client-loaded JavaScript file):
Router.map(function () {
this.route('client', {
path: '/client/:_clientName',
before: function () {
this.subscribe('client', this.params._clientName).wait();
}
}
}
Then a URI like http://yourapp.com/client/A would cause the client template to render (by default it uses the same name as the route name, unless you specify a different name) subscribing to the client subscription using "A" as the subscription parameter. This would be paired on the server side with:
Meteor.publish('client', function (clientName) {
// Clients is a Meteor collection
return Clients.find({clientName: clientName});
});
So that's how to process links after they've been generated. As for creating them, just work backwards: what query parameters are you passing to your subscription (that in turn get put into the find() call to MongoDB)? Identify each of them and write some code that adds them to an appropriate URI—in this case, your function would simply concatenate "http://yourapp.com/client/" with clientName, in this case "A". Obviously much-more-complicated routes/URIs and queries are possible, for example http://yourapp.com/events/2012-01-01/2012-12-31 with an Iron Router route path of /events/:_fromDate/:_toDate and so on.

Categories