How to get a particular html/php page and push it to my localhost.Can we do it with javascript? if yes please tell me how. Or please tell any other methode. Thank you.
Category: javascript
Category Added in a WPeMatico Campaign
Axios GET request working in plain js but not working in react – CORS error
When I make a GET request inside in react, I get blocked by CORS policy error. However if I make the same request inside vanilla js (a simple .js file) I get the appropriate response.
Here is my code in the react:
const axios = require('axios');
function getLatestPrice() {
const config = {
url: 'https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000',
method: 'GET'
};
return axios(config);
}
exports.getLatestPrice = getLatestPrice;
I get the following error:
Access to XMLHttpRequest at 'https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My code in vanilla js file
const axios = require('axios');
const url = "https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000";
const config = {
url: url,
method: "GET"
};
axios(config).then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
});
Here I am getting the correct response.
(I am not controlling the API backend)
Is there some kind of size limit when using range requests in Chromium browser?
I use following code to make range request to some large model file on the server, and then display the model using Cesium:
const m = 1024 * 1024 * 3;
Axios({
url: option.url,
method: 'head'
}).then((res) => {
const size = Number(res.headers['content-length']);
const length = parseInt(size / m);
const arr = []
for (let i = 0; i < length; i++) {
let start = i * m;
let end = (i == length - 1) ? size - 1 : (i + 1) * m - 1;
arr.push(this.downloadRange(option.url, start, end, i))
}
Promise.all(arr).then(res => {
const arrBufferList = res.sort(item => item.i - item.i).map(item => new Uint8Array(item.buffer));
const allBuffer = this.concatenate(Uint8Array, arrBufferList);
primitive = viewer.scene.primitives.add(
new Cesium.Model({
gltf: allBuffer,
show: true, // default
modelMatrix: modelMatrix,
scale: parseFloat(option.scale) || 1,
})
);
})
})
The downloadRange method goes like this:
downloadRange(url, start, end, i) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open("GET", url, true);
req.setRequestHeader("range", `bytes=${start}-${end}`);
req.responseType = "blob";
req.onload = function (oEvent) {
req.response.arrayBuffer().then((res) => {
resolve({
i,
buffer: res,
});
});
};
req.send();
});
}
When the m(range size) is smaller than about 1024*1024*6 (about 6mb), the request would be returned successfully, however when m is larger than that, the browser would say GET <url> net::ERR_FAILED 206 (Partial Content) and the request would fail. When I use postman to test the service it would return normally with a much larger size(30mb) so there should be no problem on the server side. I wonder what would cause this? Is there some kind of limit on chromium? Is there any way to get around it? Thanks for any reply in advance.
This would happen both on Chrome and Edge, and maybe other browsers.
Apply styles when scrolling to a certain element
I try that when you scroll to a certain point (which will be a div with an id) some styles or others are applied, but it does not work.
var punto1 = window.scrollY;
var punto2 = document.querySelector("#section2").scrollY;
if(punto1 > punto2) {
document.querySelector("#botella").style.display = "none";
} else {
document.querySelector("#botella").style.display = "flex";
}
});
Service and Controller Layers, Business Logic and Project Structure with Node.js
I come from a decade of experience with Java EE, SE and Java with Spring. If there’s something that was drilled in me by myself and other fellow developers, was how to make use of design patterns, separation of responsibility, separating definition from implementation, interface segregation, etc. Also, we were always worried about testable code (unit testing and integration tests).
When I was learning Java, there wasn’t a single book, magazine or website that didn’t implemented things with those rules in mind, to the point of boredom. So we always new how things should be done from an architectural point of view when starting new stuff or maintaining code. With time, projects like Spring Boot and JBoss Seams started to give you out of the box a basic project layout witch you simply followed to success(or at least you should…).
Now that I delve deep in Node.js, I miss that so much. There seems to be only a handful (and I mean it! google it and you’ll see…) of people on the web worried about it and trying to teach newcomers how to write good backend code with Node.js.
The smashing majority of people teach you how to boot express and put all of your code (database, logging, mailing, error handling and so on) inside an express route and they walk out of it fine, as if they have done a great service to mankind, and you supposedly are now already able to go out and find a good paying job for yourself.
Of course, when I started learning Java, there was nothing preventing you from using Servlets directly with some JDBC code thrown inside, or even worse, Scriptlet inside JSPs… But if you did that, that meant you were lame, slow-witted, unfit for serious duty, or suffered from some kind of brain damage. The cool guys wouldn’t want to be seen around in your company, and you would have lunch alone in the cantina every day, on a table reserved only for yourself.
So here I am, asking please, can you guys point me into the right direction? Or at least, away from the wrong ones. I would appreciate so much to know how you guys for instance implement a service layer, where do you put your business logic? that sort of thing… Do you put it in classes or functions that returns other functions? How to write easily testable code by Mocha for instance… Do I really need a controller layer, or can I trust my routes to cover that responsibility? I’m totally lost on that. Of course, I’ve come around with some solutions of my own (some even silly…), but I want to hear from the pro, from the battled people, from the veterans.
I’m interested in JavaScript only on the Backend, using Express.js, Socket.io, RabbitMQ, Passport.js, and GraphQL(in the future). Not interested in any rendering engine or template engines, much less JavaScript on the Browser. I’m already very proficient with Sequelizer and Mongoose.
Thank you guys and girls so much and sorry for my frustration, I hope you guys understand, and could perhaps even relate.
unable to redirect to the line from where the action method is called in mvc
I have the following script code.
<script>
function Save(id, cabinsId) {
var Fid = id;
var cid = cabinsId;
window.location.href = '@Url.Action("signUp","User")';
$.ajax({
method: 'GET',
url:'/Flights/ReserveFlight',
data: { FlightId: Fid, CabinId: cid }
});
}
</script>
Here in this script, I called the first action method signUp in the User controller on this line
window.location.href = '@Url.Action("signUp","User")';
from this line the called function gets executed successfully.
here is the function
public ActionResult signUp()
{
List<Gender> genders = db.Gender.ToList();
ViewBag.gender = new SelectList(genders, "Genderid", "P_Gender");
List<City> cityList = db.Cities.ToList();
ViewBag.cityList = new SelectList(cityList, "CityId", "CityName");
return View("_SignUp");
}
[HttpPost]
public ActionResult signUp(Pessenger pessenger)
{
if(ModelState.IsValid == true)
{
db.Pessengers.Add(pessenger);
db.SaveChanges();
Session["UserId"] = pessenger.PessengerId;
}
return View();
}
In the user controller, the user gets signed up. but at the end of httpPost version signUp method, I am unable to return to the script code from where I called the signUp method.
Is there a way to access JS global window object and its properties via AssemblyScript?
I’m trying to compile an assemblyscript code that reaches the JavaScript API fetching window and document objects, also adding properties to them.
In rust and the library wasm-bindgen I managed to do that with web_sys::window() plus js_sys::Reflect::set.
Is there a way to do the same thing in assemblyscript? The only library I found wasn’t updated during the last 10 months and doesn’t seem to work anymore (asdom).
Table pagination
How to make the number of pages count how many ‘trs’ there are, after removing ‘tr’, the number of pages remains unchanged.
In short, it is necessary that the numbering adjusts to the number of ‘trs’.
If the code is inserted into $("#fieldset-equipment-table fieldset").on("input", function ()
then it will duplicate the numbering
$(function () {
var $tbody = $("table tbody");
var $trs = $("tr", $tbody);
$("#fieldset-equipment-table fieldset").on("input", function () {
$tbody.innerHTML = "";
$tbody.append($trs);
$.each($trs, function () {
var $subject = $(this).data("subject");
var $search = $("[name='search']").val().toLowerCase();
if ($search && $subject.toLowerCase().indexOf($search)) {
$(this).remove();
return;
}
});
if ($tbody.children().length == 0) {
$tbody.append("<tr><th colspan=" + $("table thead tr th").length + ">No results</th></tr>");
}
});
$("table").each(function () {
var currentPage = 0;
var numPerPage = 10;
var $table = $(this);
$table.bind("repaginate", function () {
$table.find("tbody tr").hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
});
$table.trigger("repaginate");
numRows = $table.find("tbody tr").length;
var numPages = Math.ceil(numRows / numPerPage);
var $pager = $('<div class="pager"></div>');
for (var page = 0; page < numPages; page++) {
$('<span class="page-number"></span>').text(page + 1).bind("click",{newPage: page},function (event) {
currentPage = event.data["newPage"];
$table.trigger("repaginate");
$(this).addClass("active").siblings().removeClass("active");
}
)
.appendTo($pager)
.addClass("clickable");
}
$pager
.insertBefore($table)
.find("span.page-number:first")
.addClass("active");
});
});
#fieldset-equipment-table fieldset {
display: grid;
width: 600px;
gap: 2px;
place-items: stretch;
grid-template-columns: repeat(3, 200px);
margin: 20px auto;
}
#fieldset-equipment-table fieldset > div {
text-align: center;
}
#fieldset-equipment-table fieldset .kind, #fieldset-equipment-table fieldset .stats {
display: flex;
flex-direction: column;
text-align: left;
}
.fieldset-equipment-table fieldset h4 {
margin: 2px;
}
#equipment-table {
margin: 20px auto;
}
#equipment-table td:nth-child(2) {
text-align: center;
}
table {
border:1px solid #b3adad;
border-collapse:collapse;
padding:5px;
margin: 20px auto;
}
table th {
border:1px solid #b3adad;
padding:5px;
background: #f0f0f0;
color: #313030;
}
table td {
border:1px solid #b3adad;
text-align:center;
padding:5px;
background: #ffffff;
color: #313030;
}
div.pager {
text-align: center;
margin: 1em 0;
}
div.pager span {
display: inline-block;
width: 1.8em;
height: 1.8em;
line-height: 1.8;
text-align: center;
cursor: pointer;
background: #000;
color: #fff;
margin-right: 0.5em;
}
div.pager span.active {
background: #c00;
}
<head>
<title>Href Attribute Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div id="fieldset-equipment-table">
<fieldset>
<legend>Settings:</legend>
<div>
<h4>Name:</h4>
<input type="search" name="search" placeholder="Search">
</div>
</div>
</fieldset>
<table id="tb">
<thead>
<tr>
<th>Header 1</th>
</tr>
</thead>
<tbody>
<tr data-subject="Car">
<td>Car</td>
</tr>
<tr data-subject="Car">
<td>Car</td>
</tr>
<tr data-subject="Car">
<td>Car</td>
</tr>
<tr data-subject="Car">
<td>Car</td>
</tr>
<tr data-subject="Car">
<td>Car</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Cat">
<td>Cat</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>Sky</td>
</tr>
<tr data-subject="Sky">
<td>This</td>
</tr>
</tbody>
</table>
How to implement dropdown and also clickable using JavaScript or CSS or jQuery?
I want to make a dropdown which is clickable also. Like I have a menu which has dropdown options so If I hover on it, will display dropdown and if I want to click on that, it should display link that has been provided to it.
This is the HTML:
<ul class="navbar-nav ml-auto nav">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="mainservice.html" id="navbarDropdown" role="button" aria-expanded="false"> Logistics Services </a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="ftl.html">FTL</a>
<a class="dropdown-item" href="ltl.html">LTL</a>
<a class="dropdown-item" href="intermodal.html">Intermodal</a>
</div>
</li>
</ul>
So, now I want that if I click on Logistics Services then mainservice.html page should display and dropdown should also be there. It should be mobile friendly also.
I tried through CSS, but when I checked it on mobile, then it is not working as expected.
ul.nav li.dropdown:hover div.dropdown-menu{
display:block;
}
How should I do it?
category and paginator connections django html
I have a problem when I select one category and in this category when I want to go to another page it sends me just to a different page and I need it to send me to for example category=pk {{ page=2 }} or like this but now it sends to {{ page=2}}
Angular: Show html page passing value
I have a page that I use to show 3 differents html depending on where it is called.
In a page I have:
openCreateAnagraphics(){
this.router.navigate(["/anagraphics", {customerUpdate: true}]);
}
So I’m navigate to anagraphics.
there I have in my anagraphics.page.ts:
ngOnInit() {
this.handleParams();
}
handleParams() {
let params = this.route.snapshot.params;
console.log("this.route.snapshot", this.route.snapshot)
console.log("params", params)
this.customerUpdate = params.customerUpdate ? params.customerUpdate : false
console.log("this.customerUpdate ", this.customerUpdate)
}
and in the anagraphics.page.html
<div *ngIf="....">
<div>
//this is showed if I come from another way
</div>
</div>
<div *ngIf="customerUpdate">
<div>
HELLO // there is the problem
</div>
</div>
but I see only a white page and my url is
http://localhost:4200/anagraphics;customerUpdate=true
I would to obtain that I if i click on the button that calls openCreateAnagraphics, I’ll go in a page that show the html when customerUpdate = true.
For each category in discordjs?
is there a function how I can get each categorie in a guild? I want to code a Server copier which can copy a guild. So, I have to create each category and for category channels.
How to highlight all elements with the same css class when you hover over an element? I want to add mouse effect like Zoom In
I want to add mouse effects like ZOOM IN on each pricing table; However, I made the pricing tables manually so each row is not related to the previous one. I read that I have to do it using javascript, I gave each Elementor column a class name, for example, the number of users and dashboards under BASIC will have the same class. I tried a code and I was able to change the background color, but how can I add a zoom effect? I didn’t find a way to change the height and width in a function.
Thank you!
Next JS Middlewares – URLs is malformed. Please use only absolute URLs
this is the code in my _middleware file located in the pages folder it keeps giving me the
URL malformed error anytime a request is sent:
const token = await getToken({req,secret:process.env.JWT_SECRET});
const {pathname, origin} = req.nextUrl;
if(pathname?.includes('/api/auth') || token){
return NextResponse.next();
};
if (!token && pathname !== "/login") {
return NextResponse.redirect("/login");
}
}
Get Cookies of HTTP Request of ODATA Service
im facing the problem to send a put http request to an odata service. It works in Postmen with following steps:
-
Send a Get-Request with header: x-csrf-token : fetch and safe the token
-
Send a Put-Request with header: x-csrf-token : token of Get-Request
I noticed, that postmen got the same SessionID Cookie in the Get and the Put Request.
Now I want to build a fiori App, where I want to call the Odata Service.
-
I send a HTTP Get-Request with the fetchAPI whit header x-csrf-token : fetch and safe the token
-
Send a Put-Request with header: x-csrf-token : token of Get-Request.
Now I get a 403 Forbidden Error.
I checked the network tab in the dev tools of chrome and i compared the cookies of both requests. Theire sessionIDs was not equal so i thought I just need to read the cookies of the Get Request and set a Cookie Header in the Put Request to guarantee that both Requests got the same SessionID.
However this does not seem to be possible. If I read the response Header of my Get Request, i does not get the set-cookie header, although it is shown in the network tab. If i call document.cookies i just get an empty string.
So my first Problem is, that I cant read the cookies of my get request. Due to my internet research, it seems like it doesnt work becauce of cross-side problems. But im not sure about this and I do not know how I can solve this error.
In addition to that, im not able to change the cookie header in my Put request. If I set a header:
Cookie: SAPSESSIONID_ : SessionID (e.g my Postman SessionID), this headerline is not shown in my Network Tab and the Session ID of my Put Request is not the ID i wanted to be setted.
I set some headers for the response, like i read in other questions:
‘Access-Control-Allow-Headers’ – ‘Accept,Accept-Language,X-PINGOTHER,Content-Language,Content-Type,Authorization,Cookie,X-Requested-With,Origin,Host’
‘Access-Control-Allow-Credentials’ – ‘true’
‘Access-Control-Allow-Methods’ – ‘GET, PUT’
‘Access-Control-Allow-Origin’ – ”
In my request i already set credentials: ‘include’ so i think it should work. But I’m still not able to read or set any Cookies…
