Hi I want to get a custom JSON file from the stormpath API in a normal JS function instead of within a view.
The view method is like this:
var stormpath = require('express-stormpath');
app.get('/email', stormpath.loginRequired, function(req, res) {
res.send('Your email address is:', res.locals.user);
});
However when I attempt to just use the method like this:
var customD = res.send('Your email address is:', res.locals.user);
it returns an unexpected token ' ( ' error
In the posted example the quotation marks ’ are a rich encoded, not the standard single ' or double quotes ". I would replace your quotes with single quotes. What text editor are you using to write your node application?
Regarding the original question about custom data, can you show us how you are assigning the custom data properties? I suspect that you might have run into this issue: https://github.com/stormpath/stormpath-sdk-node/issues/88
Can you try the following code sample?
var stormpath = require('express-stormpath');
app.get('/email', stormpath.loginRequired, function(req, res) {
res.send('Your email address is:' + res.locals.user.email);
});
I suspect a few things:
Your code is running OUTSIDE of a route.
You have a comma in res.send(), so the send method thinks you're passing in additional arguments as opposed to a single string.
You're not using the email address directly.
Related
I am using query string using angular 10. I am sending token as parameter but it contain slashes and because of slashes it doesn't match the route. Here is my generated link
http://localhost:4200/setpassword/H/w4ee083hEr1oDsIVqMHfixizx2U48qYIIKYkdk9up21fS9atE30vQKQDA29qsYPyqMQF1E7DknJnlSHft+7OcybB0wXOoZVVABalNbeXcCTTvEarm8EdnJ6ZA19N0nwsIUl8l4ZW59GmV2pyWhxwPgpiXkxzI5mevT2xM1C7H0r/SQQLt9FOrdwR6EyAdTrQvqOlfYEkM7SJyjq+uH2ONleV1BiD9Kook/O2npX77KzVZDdLQLwPyL+yixJlsOCRWlQt1F4GCksQ983+m2341rro9w4k2yx7Jjj5AOiYSiujFIg8VVFaabEAd0Atyc7//T+x7ZX1QrM3YqOITQooNsssobQ0cDReSXneShkW6Zx0hb/cBj30DaNoVqNOa+3E2EK6PSSu31Q6UHQOxuo7Nw1MIVyBIHTvzUzT1WMoVqku78AopuWA6CAnFtt5o4GuLdz1bi6J0Lg6Sr0JGgZFlfOnRlZRoOvE8kxDbbVhEZnv3ezf8jhFR+obpgEnQ6qI+UQl0768QiZDnNDbEW9SIMXJGP4kCkXrMqmk6shvUr00S4z98vJMaI+rBRemxgK5+iVo0TcA+SAr8GhxCGdip3q4ehqrud7wWxi+8088Tjx2eED4DjwggEad3Ap9hmm/1JEqCV58F5rx+Y306G8ucYn7a/Ms8qsrh6+ctR9IW/0rxWq6qWHBbiAwwjQiL5
Here is my rout configuration
{path: 'setpassword/:token', component: SetpasswordComponent }
I want to fetch token like this but gives me nothing.
this.objModel.token = this.route.snapshot.paramMap.get('token')
Here is the code I am setting url
var url = _appSettings.EmailUrl+ token;
Basically the problem is with slashes in your token which causes the problem. You need to encode the token and then send it as parameter.
var url = _appSettings.EmailUrl+ HttpUtility.UrlEncode(token);
This will helps remove slashes and put %2 sign instead. But when you use it you must decode this token to get back your token for further procedure.
I'm sending a parameter to my Controller via json which contains and ampersand and the string gets cut off after that character. Been searching for hours and cannot find a solution.
JavaScript
var url = '/Common/DownloadFile?fileName=Me&You.xlsx';
$.ajax({
type: 'POST',
url: url,
data: {},
success: function (data) {}
});
Controller
public ActionResult DownloadFile(string fileName)
{
// Here the param is coming in as 'Me'
// Code removed for clarity
}
In urls & needs to be escaped because it is used to add new params like
http://hello.com"?fileName=Something&otherFileName=SomethingElse
You need to escape the ampersand by percent encoding it like this:
/Common/DownloadFile?fileName=Me%26You.xlsx
Here is more information on url parameter escaping escaping ampersand in url
The ampersand is used to separate arguments in a URL. If you want the ampersand to be part of a parameter value, you need to URLencode it using a method like encodeURIComponent().
In this particular case, the encoded version of Me&You.xslx would be Me%26You.xlsx. If you specify that in your GET request your application should get the expected value.
I have successfully implemented serving static files using res.sendFile() but it doesn't works if I add some querystring.
E.g. the below code works absolutely fine.
res.sendFile(path.join(__dirname, '../public', '/index.html'));
But if I do this, it fails
res.sendFile(path.join(__dirname, '../public', '/index.html?id=' + req.params.id));
res.sendFile(path.join(__dirname, '../public', '/index.html?id=123'));
Then I get the below error
ENOENT, stat '/Users/krishnandu/Documents/Project/public/index.html?id=123'
404
Error: ENOENT, stat '/Users/krishnandu/Documents/Project/public/index.html?id=123'
at Error (native)
You cannot pass query string parameters with res.sendFile(). You have to specify the file path as the 1st parameter in res.sendFile()
Syntax is :
res.sendFile(path [, options] [, fn])
So what you can do is,
Use the query string with a route, say route1 (refer the below code)
Inside the GET method of route1, use res.sendFile()
app.get('/route1',function(req,res){
res.sendFile(path.join(__dirname, '../public', '/index.html'));
});
res.redirect('/route1?id=123');
See also Express API documentation of res.sendFile and res.redirect.
This answer is to further add on to #Marie Sajan's answer by covering the question asked by #Sky in a comment.
To access id in index.html after using #Marie Sajan's answer you can use normal client-side javascript. You could do something like this in <script> tags in your html file:
var query = location.href.split("?")[1];
This would get you a string such as "id=123&name=ted".
From here you can use javascript to get the value of id. The full code might look something like this:
var query = location.href.split("?")[1]; //A string of all parameters in the URL
var params = query.split("&"); //Turns the string into an array of parameters
var id; //To store the value of id
params.forEach((param, index) => {
//This checks each key-value pair, in the format key=value, for the specific id key we want
var key = param.split("=")[0]; //In id=123, this would be "id"
var value = param.split("=")[1]; //In id=123, this would be "123" (as a String)
if (key == "id") id = value;
});
Now the javascript variable id will contain the value "123".
If you were also looking for the values of more query parameters in addition to the id key, you would simply add more if statements inside the forEach to check for those specific keys.
In a link such as "http://google.com/?q=stack+overflow&id=123", this code would be able to get the value "123" of id when implemented as client-side javascript either directly in the HTML file in <script> tags, or in a separate client-side js file that is used by the HTML file. Note that #Marie Sajan's answer is entirely server-side code, while this code is what would be used on the client-side.
This answer does not address the original question, it only adds further useful content to an accepted answer to the question based on the needs of viewers of this page.
I'm trying to call my ServiceNow JSON web service. I'm getting an unexpected error when I execute URLFetchApp. I'm guessing I'm passing in the authorization headers in the wrong way but both the GAS and ServiceNow documentation is beyond terrible. I've seen some of the other SO questions similar to this but none have worked. Any help would be appreciated.
function getOpenTickets(){
var headers = {
"Authorization":"Basic RgRJ5U6EsxHt00229KX5Hj0WV1z18q08==",
"Content-Type":"application/json",
"Username":"myusername",
"Password":"mypassword"
}
var url = "https://mysninstance.service-now.com/u_equipment_repair.do?JSONv2=&sysparm_view=vendor&displayvalue=true&sysparm_action=getRecords&sysparm_query=state=500^assignment_group.name=MyGroup^ORDERBYDESCnumber";
var url = encodeURIComponent(url);
var options = {
"method":"get",
"headers":headers
}
var result = UrlFetchApp.fetch(url,options);
Logger.log(result.getContentText());
}
OK so I found the solution. There were actually two problems.
The first was with the way I was passing the authorization headers. I was passing the basic authentication as an already encoded base64 string, on top of which I was still passing the username and password which was redundant. For whatever reason Google Apps Script (GAS) doesn't like this. Once I changed the headers and the options as shown below it was fine.
The second problem was the the URI encoding. The query string did need to be encoded because of the caret "^" symbols, but for whatever reason GAS's encodeURIComponent was not encoding it properly. As soon as I manually replaced the caret symbols with their URL encoded equivalents , which is "%5E", everything worked fine and I was able to retrieve my ServiceNow data via Google Apps Script.
function getOpenTickets3(){
var headers =
{
Authorization : "Basic " + Utilities.base64Encode('myusername:mypassword'),
"Content-Type":"application/json"
}
var options =
{
"method" : "get",
"headers": headers
};
var url = "https://mysninstance.service-now.com/u_equipment_repair.do?JSONv2=&sysparm_view=vendor&displayvalue=true&sysparm_action=getRecords&sysparm_query=state=500%5Eassignment_group.name=Somevendor%5EORDERBYDESCnumber";
var result = UrlFetchApp.fetch(url,options);
Logger.log(result.getContentText());
}
You are URI encoding your entire URL in this line:
var url = encodeURIComponent(url);
In your URL, the base path needs to be unescaped when passed to fetch(...):
https://mysninstance.service-now.com/u_equipment_repair.do
Each parameter following the ? is a URI component, like:
sysparm_view=vendor
In this case, the parameter name is sysparm_view and the value is vendor, you would need to URI encode the value (vendor) if it contained special characters like one of /?&.
In the static URL you provide, there's actually nothing that needs to be encoded, so removing that call to encodeURIComponent(url) should work.
If you are dealing with dynamic values for your URL parameters, then you'd want to URI encode each parameter value separately, before concatenating onto the main string.
I want to let user enter special characters such as "&" and then convert those to correct html when page is submitted. ex "&" => "&" I have read the examples and found ng-bind-html and $sce.
It seems ng-bind-html is useless for my need as it will only show html text sent from controller properly converted in the view. ex: it will show "&" as "&" to the user. So what I'm doing is converting the characters using "$sce" at the controller before sending it to server. Ex:
var accountName = $sce($scope.accountName);
Is this the correct way to do this? Or is there a straight forward way to bind the view to pass sanitized text to the controller, just like ng-bind-html but in a two-way binding? I'm using Angular 1.2.4.
Based on references and examples found under ngSanitize module included in angular-sanitize.js, the ideal way to parse input into properly escaped html string, is by using $sanitize component. Ex:
var accountName = $sanitize( $scope.accountName );
For this, it is required to include ngSanitize in the angular app module:
var myapp = angular.module('myapp',['ngSanitize']);
and included $sanitize in the controller where $sanitize is used:
myapp.controller('myctrl', [ "$scope", "$sanitize", function ( $scope, $sanitize) {
// code goes here
var accountName = $sanitize( $scope.accountName );
// further processing after sanitizing html input goes here
}
}]);
$sce is a service in angular that provides Strict Contextual Escaping, in which angular requires binding in certain contexts with values that are safe to be used. Further information can be found in angular documentation.