I want to call LESS's darken() function on whatever the current color is (I don't have the current color in any variable). Is that possible?
as per seven-phases-max request; in your node backend let say express
var less = require('less'); //also the body parser, express, etc
....
from your page you make an asynchronous request with the actual color of your page, just grabbing it with js and making the request. then in express:
app.post('/whateveryourroute', function(req, res) {
var colorFromReq = req.body.color;
less.render('.class { color: darken(`colorFromReq`, 20%) }', function (e, css) {
res.header("Content-type", "text/css");
res.send(css);
});
});
Something like that would be, didnt test it, but is possible.
Related
Let's say I have this in a test:
await t.expect(Selector('input')).ok()
And I would like to have (something like) this:
let func = 'ok';
await t.expect(Selector('input'))[func]()
This is so that I can have a map from selector to function, in order to iterate
over it and check whether some elements are in the page (ok) and some not (notOk).
My above attempt does not work and returns with an interesting error:
code: 'E1035',
data: [
'SyntaxError: test.js: await is a reserved word (325:14)'
]
I believe this is because Testcafe is doing some magic under the hood.
What would be the correct syntax to make it work?
It seems that you skipped the Selector property that you want to check (e.g. exists, visible, textContent, etc.). The following test example works properly with TestCafe v1.14.2:
import { Selector } from 'testcafe';
fixture`A set of examples that illustrate how to use TestCafe API`
.page`http://devexpress.github.io/testcafe/example/`;
const developerName = Selector('#developer-name');
const submitButton = Selector('#submit-button');
test('New Test', async t => {
await t
.typeText(developerName, 'Peter Parker')
.click(submitButton);
let assertFunc = 'ok';
await t.expect(Selector('#article-header').exists)[assertFunc]();
});
My thing is a small project.
In main what it does is that the "server" will get a call from the link directly what will run some functions that will update the database and the data that has to be shown.
I will show what I mean:
function updateData(){
connection.query(`SELECT * FROM muzica WHERE melodie = "${updateList()}"`, function (error, rezultat, fields) {
if (error) {console.log('err la selectare')};
//express output
let data = {
melodie: rezultat[0].melodie,
likes: rezultat[0].likes
}
console.log(data.likes);
app.get('/like', (req,res) =>{
res.json(`${data.likes}`);
});
}
setInterval(()=>{
updateData();
}, 20000)
Uhh, how to explain it, I'm so bad at this...
So, in main, I'm new to back-end work, everything that I did was based on their Documentation as I learn way faster by my needs than some guides and so on.
So, when I or someone does my http://website/like it should show just data.likes, cause that is all that I need, don't count data.melodie (i will clean that later on) after I finish all the code.
Anyway, whenever I do website/like data.likes is not updating to the new database data.likes.
For example, data.likes before were 5, in a few minutes it can be 2 but whenever I call website/like show "5" than its new value 2.
Don't be hash on me, I'm new and I want to learn as much as I can, but I can't understand the above case, by my logic it should ALWAYS show what its in database when it refreshes each 10 seconds(I run this in localhost so I will not stress any online server).
But if there is any better way to check for databases update than "setInterval" please notice me.
It's hard to learn alone without a mentor or someone else to talk about this domain.
Thank you for your time!
Kind regards,
Pulsy
You have things a bit inside out. A request handler such as app.get('/like', ...) goes at the top level and you only ever call it once. What that statement does is register an event handler for any incoming requests with the /like path. When the server receives an incoming request for /like, it will then call the function for this route handler.
You then put inside that route handler the code that you want to run to generate the response and send the response back to the client.
app.get('/like', (req, res) => {
connection.query(`SELECT * FROM muzica WHERE melodie = "${updateList()}"`, function (error, rezultat, fields) {
if (error) {
console.log(error);
res.sendStatus(500);
} else {
//express output
let data = {
melodie: rezultat[0].melodie,
likes: rezultat[0].likes
}
res.json(data);
}
});
});
The endpoints need to be outside of any functions in express.
For example, if you look at the express "hello world" example here, you will see that they have a basic app that only has a single GET endpoint defined which is "/" so you would access it by running "localhost/" or "127.0.0.1/".
In your case, you want your endpoint to be "/like", so you must define something like:
const express = require('express')
const app = express()
const port = 3000
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
app.get('/like', (req, res) => {
// do database stuff and assign data variable
// res.json(data);
}
I'm trying to keep this variable in the callback:
var that = this
// type1
bootbox.confirm("This is the default confirm!", function(result){
console.log(that.whatever);
});
// type2
bootbox.confirm({
message: "This is a confirm with custom button text and color! Do you like it?",
callback: function (result) {
console.log(that.whatever);
}
});
It looks ugly, is there any better way to do it?
You can use an arrow function:
bootbox.confirm("This is the default confirm!", result => {
console.log(this.whatever);
});
You should compile this with Babel though, older browsers may not support it. If you have the callback as a variable, you can bind it before passing:
yourCb.bind(this);
bootbox.confirm("This is the default confirm!", yourCb);
I'm having a little trouble setting one of my this.values within my Vue application. I believe I'm either not understanding async axios calls correctly, or how async works within axios.
I have the following axios post method within my Vue application:
postRequest: async function(event) {
event.preventDefault();
let config = {
headers: {
"X-CSRFToken": this.csrfToken,
"Content-Type": 'application/x-www-form-urlencoded',
}
}
let formData = new FormData();
formData.append('data', someData);
await axios.post('{{ request_absolute_uri }}', formData, config).then(function(response) {
this.responseMessage = response.data.message;
}).catch(function(error) {
console.log(error);
});
}
console.log(this.responseMessage)
return this.responseMessage;
}
My response.data.message is being passed back from my framework as True/true but it seems I'm not returning anything from the postRequest function? The post definitely hits the server as logging shows everything I want - then returns back message = true in json response context (using console.log(this.responseMessage) directly before returning the same value. However, nothing on the template changes or updates from this....
I'm assuming at this point that I have missed something incredibly simple!
Hmmm. I think I know what is going on here: because you're using a standard function, your this inside the .then() callback is not refering to the instantiated object...instead, this. is the calling the context of that function - with your original code, i.e., the Promise returned by the axios .post method.
Instead, I would advise using an arrow function instead so that the this is inherited from the outer scope, something along these lines:
await axios.post('{{ request_absolute_uri }}', formData, config).then( (response) => {
this.responseMessage = response.data.message;
})
N.B. With arrow functions, the this. is always inherited from the outer scope, rather than depending on the calling context of the arrow function - so you can reference this.message or this.someFunction() with ease.
I believe the "this" is out of scope inside .then statement. If you add the line:
var self = this;
at the top of your postRequest function, and then when assigning the response message use:
self.responseMessage = response.data.message;
I think that should work.
I am fairly new to JavaScript, and I have been having issue with the scope of what I think is a global variable.
Here is where I receive the data from the user via Socket.IO: (server.js)
var locationData = {lat: '-20', long: '20'};
var latNumber;
var longNumber;
//SocketIO data
var chat = require('express')();
var http = require('http').Server(chat);
var io = require('socket.io')(http);
io.sockets.on('connection', function (socket) {
socket.on('new message', function (msg) {
locationData = msg;
latNumber = parseFloat(locationData.lat);
longNumber = parseFloat(locationData.long);
io.emit('message', msg.message);
});
});
http.listen(5670, function(){
console.log('listening on *:5670');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
function getLat(){
return latNumber;
}
function getLong(){
return latNumber;
}
Here is the HTML script where I want to receive that data: (HelloWorld.html)
<script type="text/javascript" src="/server.js"></script>
<script>
var viewer = new Cesium.Viewer('cesiumContainer');
var citizensBankPark = viewer.entities.add({
name : 'Test',
position : Cesium.Cartesian3.fromDegrees(getLat(),getLong()),
point : {
pixelSize : 5,
color : Cesium.Color.RED,
outlineColor : Cesium.Color.WHITE,
outlineWidth : 2
},
label : {
text : 'Test',
font : '14pt monospace',
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
pixelOffset : new Cesium.Cartesian2(0, -9)
}
});
viewer.zoomTo(viewer.entities);
</script>
I am trying to read the data from latNumber and longNumber defined and set in server.js into the position assignment in HelloWorld.html. The problem I am having is that once the data gets to HelloWorld.html it is undefined, and gives an error in the browser.
Now what I am not sure about is why is it undefined. Logging the latNumber and longNumber variables in server.js work fine and have data in them. Also changing the return statements in the getLat() getLong() to a hardcoded variable such as 15 works fine, and passes it onto HelloWorld.html, where it then does what it is supposed to do. It only errors out when I combine the two together!
Any help or pointers would be much appreciated! Thanks!
You've got quite a mix of issues here. Your server.js file doesn't look like client-side code at all, it looks like it's supposed to be running the server via Node.js. Are you using Node.js to run server.js to listen on port 5670, as this code suggests?
If so, good, but get rid of the <script src="/server.js"> reference on the client code. You don't want the client reading the server's source code (and ideally it shouldn't even be served, but that's a different topic).
So now you have a new problem: Your server has getLat and getLon functions that no longer exist at all on the client. You need to transmit the information from server to client.
In server.js, you can add some code to make these numbers available via REST:
chat.get('/location', function(req, res, next) {
var response = {
lat: latNumber,
lon: lonNumber
};
res.type('application/json');
res.send(JSON.stringify(response));
});
This server code will listen for requests for the URL /location and respond with a JSON string containing the numbers.
Next, your client code should request these values from the server, asynchronously (meaning we don't lock up the browser's UI while waiting for the server to respond). This is done like so:
var viewer = new Cesium.Viewer('cesiumContainer');
Cesium.loadJson('/location').then(function(data) {
viewer.entities.add({
name : 'Test',
position : Cesium.Cartesian3.fromDegrees(data.lon, data.lat),
point : {
pixelSize : 5,
color : Cesium.Color.RED,
outlineColor : Cesium.Color.WHITE,
outlineWidth : 2
},
label : {
text : 'Test',
font : '14pt monospace',
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
pixelOffset : new Cesium.Cartesian2(0, -9)
}
});
viewer.zoomTo(viewer.entities);
});
In the above code, loadJson returns a promise to get the data, and we add a callback function to execute when the promise resolves. The callback receives the server's data as a parameter, and builds a new entity. You can see the entity's position is based on data received from the server.
If the server's idea of the location changes, you may need to have the client periodically poll for the new location, or you can use a number of different technologies (long-polling, server-side push, EventSource, WebSockets, etc.) to get the client to update. But for starters, just reload the client page to see the new location.