Alright, so I have downloaded Express, set the port with process.env.PORT || 8080, and set the app variable var app = express(). Now, what I'm trying to accomplish is instead of rendering HTML through a file, could I do it through a string?
var html = "<!DOCTYPE html>\n<html>\n <head>\n </head>\n <body>\n <h1>Hello World!</h1>\n </body>\n</html>";
app.get('/',function(req,res){
res.render(html);
});
Is there a possible way to do this?
the res.render method as specified in the doc : Renders a view and sends the rendered HTML string to the client. So you need to use a template engine eg : jade,ejs, handlebars.. but if your purpose is to only output some html you can do it with res.send instead.
Use res.setHeader set HTTP Response Header
res.setHeader("Content-Type", "text/html")
res.send(`
<h1>Mock API</h1>
`)
You could do it with a string but then you should convert the call to a Javascript call so only the part that needs to be replaced is displayed on the web page. The Ajax call gets from the Controller a : res.send("This is a String) back to its client. At the client you could put this result in a elements innerHtml and then you will have some kind of SPA :-)
Related
Im making a discord bot, and I have a URL here which has some raw json: link here and I want one of the values (hashrateString) to be put inside a embed like:
hashrateString: 1GH
is there a way to do that and if so how?
I never tried this with an external link but it should work the same way.
FIRST: write somewhere high up in your code this line
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('http://ric.pikapools.com/api/stats', 'utf8'));
After you can basically do whatever you want with your new object. There was no hashrateString: 1GH, but hashrateString: 4.68 GH should be accessible with data.algos.primesr.hashrateString (Output: 4.68 GH)
If it, for some weird reason, doesn't accept an URL, just try to copy&paste the text in a json file if possible, and use the path to it
I was able to get this to work by specifying a constant to be the JSON from the url using node-fetch
const ricp = await fetch('http://ric.pikapools.com/api/stats').then(response => response.json());
and find an object in the JSON using
message.channel.send(ricp.algos.primesr.hashrateString)
I'm using angular 4 innerHtml element for parsing Html from the server.
<div *ngFor="let html of htmlToRender">
<div [innerHtml]="html"></div>
</div>
I'm using API to get HTML from the server and the response I'm using JSON.parse() method to parse the response type.
it gives me the array
this.htmlToRender = JSON.parse(this.htmlToParse._body);
now the problem is when i'm rendering this.htmltoRender i may get some image or file URls which are having absolute path.
eg:
<img alt="" src="/Source/ImageBrowser/Image?path=logoCar.qd.png"
from the server, I will get such path... I need to add Url to access that source example: for the response, I need to append example "http://google.com"
ie.,.
<img alt="" src="http://google.com/Analytics/ImageBrowser/Image?path=logo.qd.png">
since parsing from the server they are not able to append
so any idea how we can achieve this in angular 4?
I think this happens due to angulars security mechanisms. Try using the DomSanitizer as described here.
Example:
updateVideoUrl(id: string) {
// Appending an ID to a YouTube URL is safe.
// Always make sure to construct SafeValue objects as
// close as possible to the input data so
// that it's easier to check if the value is safe.
this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
}
You can try to replace all urls after you get the result from the server using a regular expression. Look for all occurrences of /Source/ImageBrowser/, and replace them with your desired url.
var regExp = new RegExp(/\/Source\/ImageBrowser\/*/g);
this.htmlToRender = this.htmlToRender.replace(regExp,'http://google.com/Analytics/ImageBrowser/');
Replace the occurance in Component itselef instead of in html for performance reasons,
Since you have array in this.htmlToRender,
this.htmlToRender.forEach(html => {
html = html.replace("/Source", "http://google.com/Analytics");
})
If you want to replace using regExp
this.htmlToRender.forEach(html => {
html = html.replace(/\/Source/i, "http://google.com/Analytics");
})
If /Source/ImageBrowser is not the same then you can do,
this.htmlToRender.forEach(html => {
let imageUrl = a.split('/');
imageUrl = imageUrl[imageUrl.length - 1]
imageUrl = "http://google.com/Analytics/ImageBrowser/" +imageUrl
html = imageUrl
})
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.
I have a simple Backbone.js/Bootstrap front end in HTML5 with a Node.js/Restify backend. I am setting cookies in a header response from the server as below:
res.setHeader("Set-Cookie", ["token=ninja", "language=javascript"]);
On the client side, I am making a REST call as
var response = this.model.fetch().success(function(data){
//success
}).error(function(data){
//error
}).complete(function(data){
//complete
});
that callsback a parse method in the model.
How can I read the cookie value in the model?
Include Cookie.js.
You can then reference individual cookies like this:
var token = Cookie.get('token')
# token == 'ninja'
Here is what I figured out. My application has two components - the HTML/js from one domain that talks to a REST sevice on another domain (and therefore is cross-domain.) Because the cookie is set from REST, it appears is not readable across domains. So the web page will not store the cookie even though the server is sending it. One alternative is to use local cookies or use the technique illustrated by http://backbonetutorials.com/cross-domain-sessions/.
Assuming you are using jQuery with Backbone, you can get the headers by defining the parse function in your model by calling getAllResponseHeaders or getResponseHeader:
var model = Backbone.Model.extend({
// the rest of your model
parse: function(resp, xhr) {
var allHeaders = xhr. getAllResponseHeaders();
var cookieHeader = xhr. getResponseHeader("Set-Cookie");
// do something with the headers
return resp;
}
});
I want to update two different values with one ajax-response.
<span id="nr1">Change this</span>
<span id="nr2">and change this</span>
Now I can just change one value, I do like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText;
Is it possible to do something like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText1;
document.getElementById('nr2').innerHTML = xmlHttp.responseText2;
**** UPDATE ****
The response comes from php.
I'm totally new to JSON.
There are no responseText1 and responseText2 properties of an XMLHTTPRequest(which I assume your xmlHttp is), just responseText, so you have to return something parsable in that responseText field(like JSON). So you server may send back {"firstResponse":"value1","secondResponse":"value2"} and you can fill your fields from that JSON string. Use the json2.js library from json.org
<script type="text/javascript" src="json2.js"></script>
. . .
var theResponse = JSON.parse(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = theResponse.firstResponse;
document.getElementById('nr2').innerHTML = theResponse.secondResponse;
EDIT:
In order to craft this JSON response from PHP you should use the PHP JSON libraries. There are several examples in the json_encode page that can get you started. The other code I posted(and that is posted in other responses) are all browser side javascript code.
$arr = array ('firstResponse'=>'value1','secondResponse'=>'value2');
echo json_encode($arr);
Place that code into your PHP script to generate the JSON string
{"firstResponse":"value1","secondResponse":"value2"}
Then the previously posted javascript code will parse that.
If you trust and control the server, just return a dictionary in JSON for the response and use it on the client side. So:
v = eval(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = v['nr1']
document.getElementById('nr2').innerHTML = v['nr2']
As already said it would make sense to return your Ajax call as a JSON Object. I recommend the more secure JSONP call (don't know if you can use any library that supports this natively).
// Your script returns this
callback123(
{
"nr1" : "This is conten for nr1",
"nr2" : "Some content for nr2"
});
// JavaScript callback looks like this
function callback123(data)
{
for(var key in data)
document.getElementById(key).innerHTML = data[key];
}
use JSON.parse
link text