I got this code for a weather app that I am building in NodeJS. when I receive the response from the nodejs I receive the details(temperature, rain) in plain text. So I cannot style it. is there any method I can use to get the response as a styled site with CSS? I cannot use a prebuilt html code cause the weather is always changing. Is there a mthod to get a styled site?
app.post('/', function(req,res){
const query=req.body.cityName;
const apiKey=' '
const url="https://api.openweathermap.org/data/2.5/weather?units=metric&q="+query+"&appid="+apiKey;
https.get(url,function(response){
console.log(response.statusCode);
response.on("data",function(data){
const weatherData = JSON.parse(data);
console.log(weatherData);
try{
const temp = weatherData.main.temp;
console.log(temp);
const weatherWescription = weatherData.weather[0].description;
console.log(weatherWescription)
const icon =weatherData.weather[0].icon;
const iconUrl="http://openweathermap.org/img/wn/"+icon+"#2x.png"
res.write("<h1> The Weather is currently " + weatherWescription + "</h1>");
res.write("<h1> Temperature is "+temp+"</h1>");
res.write("<img src="+iconUrl+">")
res.send();
}
catch(e){
res.send("Enter a Valid City Name")
}
});
});
});
Here are some of the options you have:
Your API can fetch JSON data (no HTML) and then you programmatically insert that into your page with Javascript in the web page by inserting that data into the already styled page to replace the data that is already there. This should then inherit the styling that you already have, using the existing CSS rules. If you have a client-side template system such as EJS, you could use that to generate HTML from a template stored in your page with the new data inserted into the template and then insert that generated HTML into the page. Or, you can insert the data manually into the existing HTML with your own Javascript.
Your API can fetch a piece of styled HTML that uses CSS classes and ids that will inherit the existing CSS rules already in the page. You then use client-side Javascript to insert this piece of styled HTML into your existing page and it will automatically be able to use the CSS rules already in the page.
Your API can fetch a whole new HTML body which can then insert. You can either include CSS rules in the new HTML body or you can use the existing CSS rules from the page.
Hi #Pasindu sathsara,
My understanding - you are asking for a css style change respective to response( correct me if i am deviated)
The idea is like,
Understand the api response.
Write N number of style tag w.r.t climate and keep it as node string
Have a simple switch and compare climate and get the climate
According to climate res.write(css style tag in variable ) before res.end() so that style is dynamic according to response
Regards,
Muhamed
Related
I want to scrape this link : https://www.magicbricks.com/property-for-sale/residential-real-estate?bedroom=&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment&cityName=Mumbai for the links for each property.
The link to the individual pages for each property is not in the HTML source code. The opening of the page instead is linked to an event. How do I get the links to the page that opens using Scrapy and Playwright?
Each website is different and needs to be treated differently. Usually the journey starts from the element panel of the page.
Upon taking a closer look at the elements panel of the url you have shared, we can see each card is inside a div and the div also has a script tag with a json. The json indeed has the URL you were looking for.
Here is the code to extract the URLs that you can run inside the page.evaluate function.
await page.evaluate(async () => {
const urls = [];
// parent card elements
var cardElements = [...document.querySelectorAll('[class="mb-srp__list"]')];
for(let cardElement of cardElements) {
// get nested script tag inside each card element that contains the url
const script = cardElement.querySelector('script');
// but the content of the tag is a string, so we need to parse
const cardJSON = JSON.parse(script.innerHTML);
// finally save whatever data we want
urls.push(cardJSON.url);
}
return urls;
});
Here is a shorter version of the code that can go inside page.evaluate,
[...document.querySelectorAll('[class="mb-srp__list"]')].map(card=>JSON.parse(card.querySelector('script').innerHTML).url)
I'm using the methods described here Mailto on submit button to generate a new email from inside a form. This is working well, but I'd like to extend it by populating the new email with either the entire contents of the form, or from a saved txt file (~1k) containing the same information. How can I do that? If using the saved version, I'd prefer to see the actual text rather than attaching the file, but either method is ok. I'm pretty new at html, and most of my code borrows heavily from SO, which is a wonderful resource.
IF I understood your question well, you wish to add some content in your email, in format of html or plain text.
You can achieve it using ejs library to render html/text templates in backend/server.
import ejs from 'ejs';
import fs from 'fs';
import path from 'path';
//you need to create your templates first
cosnt htmlTemplate = fs.readFileSync(path.join(__dirname, `/templates/` + fileName + '.html.ejs)).toString();
cosnt textTemplate = fs.readFileSync(path.join(__dirname, `/templates/` + fileName + '.text)).toString();
const html = ejs.render(htmlTemplate);
const text = ejs.render(textTemplate);
// and then use these html/text in your send method
Add template files - mytemplate.text:
Hi dear client!
Welcome to our community...
or mytemplate.html.ejs: ... you are going to add the same way as when you write html markup code.
I'm working on a project for school where one is able to create HTML elements by using Selection.js (visual selection turns into an HTML element). Currently, the user is able to write CSS in a CodeMirror editor. After the user applies the CSS by clicking a button, the styling is directly inserted onto the created React component trough props.
My main goal is to allow the user to create multiple elements with multiple styling rules, to then (in the end) export the created elements along with their styling.
I've imported JSS, because of the createStyleSheet function that generates styling based up on a JavaScript CSS object (which comes from the CodeMirror input) and because of the fact that the directly injected style trough props is not reusable (because it doesn't contain classes, just properties). The problem with JSS is that it generates styling in the form of .mySpecialClass-0-1 {...}
This is the code that I'm using when the user applies the style (on click).
onStyleInput(e) {
e.preventDefault();
try {
let style= cssToObject(this.codeMirror.getValue(), {camelCase: true});
this.styleSheet = jss.createStyleSheet(style, {link: true}).attach();
console.log(this.styleSheet);
}
catch (exception) {
// console.log("Something went wrong, check your css syntax");
console.log(exception);
}
}
The result I expected from JSS was styling in the form of .mySpecialClass {...}, without the unique id's.
I've been looking trough the JSS API, but there doesn't seem to be an available boolean to toggle the unique id generation.
Is there a better way of achieving my goal?
Thanks in advance!
The easiest way to have JSS classes without ID is, make it as "Global" styles. It is mean, we have global CSS styles which not attached individually to the elements. Rather than just put/set HTML className without really utilizing JSS result. They call it "Global selectors" at "plugin" section at their documentation pages.
You can find documentation here: https://cssinjs.org/jss-plugin-global?v=v10.0.0-alpha.7
I am new in React. I am attempting to make a live feed from my wordpress site. I am having trouble rendering the images associated with each article.
In the code below I log the mediaSRC variable which I am storing the url of the image. When logging this the proper URL outputs to console. However when I try to create my Post object later on after the if statement, the mediaID is = to "NO IMAGE"
When I am rendering the POST the html img is showing img src="NO IMAGE"
<div className="main-feed">
{posts.map(function(post){
//mediaSRC is eventually going to by my <img src >
var mediaSRC ="NO IMAGE";
//post.featured_media will access the media ID of the image
var media = post.featured_media;
// if there is no image set mediaSRC to this string
if (post.featured_media ==0){
mediaSRC="MEDIA ID IS ZERO";
}
// if there is an image, set mediaSRC to the url of image
else{
j.ajax(React_Theme_Resource.url + "/wp-json/wp/v2/media/" +media)
.done(function(data){mediaSRC = data.guid.rendered; console.log(mediaSRC)})
.fail(function(){console.log("FAIL")})
.always(function(){})
}
//Create Post object NOTE : working without images
return <Post post={post} mediaID={mediaSRC} key={post.id} />
})}
</div>
You are getting your image via an ajax request, but the component is not updated with the new image source. There are a couple of issues here.
It is a bad practice to make ajax request in your render method. The best place for them (if you are not using Flux, Redux or other state management library) is in the constructor.
Secondly, you need to use .setState() (again, if you are using react state to manage the state of the component and the app) method to add the new image source to the component.
You can read more about react state here: https://facebook.github.io/react/docs/state-and-lifecycle.html
I'm writing a WinJS app that takes an HTML fragment the user has copied to the clipboard, replaces their
Later, when I go to display the .html, I create an iFrame element (using jQuery $(''), and attempt to source the .html into it, and get the following error
0x800c001c - JavaScript runtime error: Unable to add dynamic content. A script attempted to inject dynamic content, or elements previously modified dynamically, that might be unsafe. For example, using the innerHTML property to add script or malformed HTML will generate this exception. Use the toStaticHTML method to filter dynamic content, or explicitly create elements and attributes with a method such as createElement. For more information, see http://go.microsoft.com/fwlink/?LinkID=247104.
I don't get the exception if I don't base64 encoded the images, i.e. leave them intact and can display iframes on the page with the page showing images.
If I take the html after subbing the urls for base64 and run it through toStaticHTML, it removes the src= attribute completely from the tags.
I know the .html with the encoded pngs is right b/c I can open it in Chrome and it displays fine.
My question is I'm trying to figure out why it strips the src= attributes from the tags and how to fix it, for instance, creating the iframe without using jquery and some MS voodoo, or a different technique to sanitize the HTML?
So, a solution I discovered (not 100% convinced it the best and am still looking for something a little less M$ specific) is the MS Webview
http://msdn.microsoft.com/en-us/library/windows/apps/bg182879.aspx#WebView
I use some code like below (where content is the html string with base64 encoded images)
var loadHtmlSuccess = function (content) {
var webview = document.createElement("x-ms-webview");
webview.navigateToString(content);
assetItem.append(webview);
}
I believe you want to use execUnsafeLocalFunction. For example:
var target = document.getElementById('targetDIV');
MSApp.execUnsafeLocalFunction(function () {
target.innerHTML = content}
);