I am trying to login in to a site with nodejs.
The site's asp.net login form has hidden fields:
__EVENTTARGET, __EVENTVALILDATION, __VIEWSTATE, __EVENTARGUMENT
I am trying the following code:
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; // Ignore 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' authorization error
var request = require('request');
var cheerio = require('cheerio');
function postback(url, callback) {
request.get(url, function onResponse(err, res, body) {
$ = cheerio.load(body);
var button = callback(err, $);
if (button) {
var form = {
//__EVENTTARGET: button.attr('form1').match(/['"]([^"^']+)/)[0], // TODO image buttons
__EVENTTARGET: button.attr('Button1'),
__VIEWSTATE: $('#__VIEWSTATE').val(),
__EVENTVALIDATION: $('#__EVENTVALIDATION').val(),
__EVENTARGUMENT: $('__EVENTARGUMENT').val(),
};
}
});
}
postback('https://example.com', function(err, $) {
var button=$('input[type="image"]');
return button
//console.log(err)
//console.log($)
})
It's not getting the values of __EVENTTARGET and __EVENTARGUMENT.
These fields may needs a button click.
How to click it with cheerio?
Related
So I'm trying to build a JS script that allows me to automatically enroll in courses in uni once they're available, and what I've gotten so far is filling the boxes with course IDs and then clicking submit but then I realized using ajax to post would be a better way than simulating a click.
The problem is, the returned html after a post is just a normal html with no success msg on enrolling neither failure. Here is my code:
const courses = ['56895', '56712', '56812']
function findnewreg() {
var index = 0
courses.forEach(element => {
index++;
var ind = "crn_id" + index;
document.getElementById(ind).value = element
form = document.getElementById(ind).form
});
var regbtn = document.getElementsByName('REG_BTN')
regbtn.forEach(element =>{
if(element.value=='تنفيذ التغييرات'){
//element.click();//<form action="/PROD/xwckcoms.P_Regs" method="post" onSubmit="return checkSubmit()">
submitForm()
console.log("clicked")
document.addEventListener("DOMContentLoaded", function(event){
if (document.body.textContent.includes("لقد قمت بإجراء العديد من المحاولات لتسجيل هذا الفصل الدراسي، اتصل بمكتب التسجيل للحصول على مساعدة. ")) {
console.log('⛔️ error retrying...');
//history.back();
findnewreg()
}else{
console.log('✅ success');
}});
}
})
}
function submitForm(){
var form = form = document.getElementById("crn_id1").form
var href = '/PROD/xwckcoms.P_Regs'//form.getAttribute("action");
var formData = {};
jQuery(form)?.find("input[type=text]").each(function (index, node) {
console.log(index, node)
formData[node.name] = node.value;
});
// formData = jQuery(form).serialize() //also tried this, same result
jQuery.post(href, formData).done(function (data) {
prompt('DATA:' , data)
findnewreg();
});
}
findnewreg();
I'm trying to allow users to type a search query into a box on an index.html page and have it send them to a results.html page with results displayed.
Currently I have this working only on an index.html page where the old HTML is removed and replaced with the search results.
//Pertinent Node code:
app.get('/', function(req, res){
res.header("Access-Control-Allow-Origin", "*");
res.redirect('index.html');
});
// A search box in index.html calls the /search below
app.get('/search', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
const item_id = req.query.item_id;
var json = {};
var sql_query = "a SQL query";
var result = connection.query(sql_query, function(err, result, fields) {
if (err) throw err;
json["result"] = result;
console.log("Sent JSON to client");
res.send(JSON.stringify(json));
});
})
//Client-side:
function get() {
var search = document.getElementById("search").value;
// Validate input to prevent injections
var new_search = search.replace("<", "");
var validated = new_search.replace(">", "");
var url = host + "/search?search=" + validated;
fetch(url, {method : 'GET'})
.then(checkStatus)
.then(function(responseText) {
var json = JSON.parse(responseText);
displaySearchResults(json, search);
})
.catch(function(error) {
});
}
What I'm trying to do is similar to what you might see on Google where clicking search send you to a new page with a url like: "https://www.google.com/searchresults?query=bicycles" that displays a different HTML page from index.html (such as results.html) with the JSON from index.html being moved to and processed in results.html.
How can I make this happen?
Adding some details to what Brad kindly mentioned in comments.. The full solution is:
<form action="search.html" method="GET" name="search">
Then in the Javascript file for search.html, access the form data with:
var search = window.location.search;
If you need to get the "?search=" out of the data, instead use:
var search = window.location.search.replace("?search=", "");
I have a problem, I used a get and post function to retrieve and save some url in my database, but now I d like to update a variable count, that should rapresent the votes that every video get, and after that I shoul be able to disable the button that a user click to vote. So I'm having some troubles to make the update function, or I should use another post? But if so I probably create another element inside my DB or not?
so here there is my video and for now I set the video's id invisible using css, to test it and try to find the video with that specific id and make the update
<p class="invisible" id="idVideo"> {{item._id}} </p>
<iframe class="partecipant" v-bind:src="item.video.url"> </iframe>
<p id="voti" > {{item.voti.count}} </p>
<input type="button" id="buttonVoti" v-on:click="addVoto">
so here, when the user click the button with id= buttonVoti the v-on click call addVoto function
methods: {
...
//ALL THE OTHERS METHODS
...
...
...
//AND THEN THE ADDVOTO FUNCTION
addVoto : function () {
var self = this;
//self.videos[1].voti.count++
//console.log(self.videos._id);
var i = document.getElementById("idVideo");
var idVid =i.innerHTML;
console.log(idVid);
so here I can change the variable count, using self....count++ but I have to store and then retrieve again the same video with the new count updated.
here there is my model so the logic to access to the count should be this one
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var videoSchema = new Schema({
video : {
id : String,
url : String,
idchallenge : String
},
voti : {
count : {}
}
});
module.exports = mongoose.model('Video', videoSchema);
yes so I have a method called load video, that is activated when the user click a button called loadVideo
loadVideo : function (){
var linkYoutube = this.text;
console.log(linkYoutube);
//POST
axios.post('/video',{
method: 'post',
video: {
id: '1',
url: linkYoutube
},
voti: {
count: 0
}
});
and this is my get function,
getVideo: function () {
var self = this;
// Make a request for a user with a given ID
axios.get('/video')
.then(function (response) {
self.videos = response.data;
console.log(self.videos);
When you do you GET request to your video route, in your route logic, you should be able to use Mongoose count. Here is what that route might look like:
var Router = require('express').Router();
var mongoose = require('mongoose');
var Video = mongoose.model('Video');
Router.get('/videos', function(req, res) {
var response = {};
Video.find({}, function(queryErr, videos) {
if (!queryErr) {
response.videos = videos;
Video.count({}, function(countErr, count) {
if (!countErr) {
response.count = count;
res.status(200).send(response);
} else {
res.status(500).send(countErr);
}
});
} else {
res.status(500).send(queryErr);
}
});
});
module.exports = Router;
Here is a question about Mongoose count on Stack Overflow.
I made a server on NodeJs using module Express. Now I want to implement a request from html page with $.ajax by clicking a button. I want to get data from server in json format or in text format, it doesnt matter, but it doesn't work. Why?
And plus why does ajax request reload the html page while it shouldn't?
Server part:
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app = express();
var url = require("url");
app.get('/scrape', function (req, res) {
console.log("Someone made request");
url = 'http://spun.fkpkzs.ru/Level/Gorny';
request(url, function (error, response, html) {
if (!error) {
console.log("Inside request");
var $ = cheerio.load(html);
var date, waterlevel;
var json = {
time: "",
waterlevel: ""
};
json.time = $("#waterleveltable td.timestampvalue").first().text()
json.waterlevel = $("#waterleveltable td.value").first().text()
res.send(json);
console.log(json);
}
})
})
app.listen('8081')
console.log('Server started on port 8081');
exports = module.exports = app;
This is my hmlt request:
<form>
<!-- button for sending a request to server-->
<button id="button12">Scrape water height</button>
</form>
<div id="response21">
Print
<!-- div for displaying the response from server -->
</div>
<p id="p1">___!</p>
<script>
$(document).ready(function () {
$("#button12").click(function () {
console.log("Get sent.")
// Json request
$.get("http://localhost:8081/scrape", function (data)
{
console.log("Data recieved" + data);
$("#response21")
.append("Time: " + data.time)
.append("Waterlevel: " + data.waterlevel);
}, "json");
});
});
Because of the fact that your button is inside a form, the default action of clicking the button will be to load a new page. This is what causes the reload of your page.
The simplest thing you can do is a return false at the end of the click handler callback so that to prevent the reload of the page.
A bit of a newbie here. I've been looking for an answer that works and found some similarities in a Jade problem but I'm not using Jade. I have passed an "user" attribute into an HTML view as so:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profilePage/profilePage.html', {
user : req.user // get the user out of session and pass to template
});
});
Then, in my profile HTML, I can access my user property like so:
<%=user.local.firstname%>'s Profile
However, I want to allow Stripe to send the user's credit card info via the Stripetoken. I have managed to include a variable amount from a text field the user inputs. However, I want to append the user property so I can use it in my callback. Here is the javascript/jquery that's included in the profile html:
<!-- New section -->
<script type="text/javascript">
<!-- Fill in your publishable key -->
Stripe.setPublishableKey('pkkey');
var stripeResponseHandler = function(status, response) {
var $form = $('#contactForm');
var $amount = $('#amount').val();
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.append($('<input type="hidden" name="amount" />').val($amount));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#contactForm').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
As you can see, I have managed to append the $amount variable so I can access it in the callback:
module.exports = function(app, passport) {
app.post('/stripe', function(req,res) {
// =====STRIPETOKEN======
var transaction = req.body;
var stripeToken = transaction.stripeToken;
var donationAmount = transaction.amount;
stripe.customers.create({
source : stripeToken,
account_balance : 0
},function(err, customer) {
if (err) {
console.log(err);
} else {
console.log("Success!");
}});
// ====CREATE CHARGE======
var charge =
{
amount : donationAmount,
currency : 'USD',
card : stripeToken
};
stripe.charges.create(charge, function(err, charge) {
if(err)
console.log(err);
else
{
res.json(charge);
console.log('Successful charge sent to Stripe!');
console.log(charge);
};
});
// ====PROFILE PAGE REDIRECT=====
res.render('profilePage/profilePage.html', {
});
});
So here's my problem. I want to pass the user's information, kind of like I did the amount, into the post method so when it redirects on success, I can pass it back in the res.render function, as well as send it to Stripe for description purposes. The only thing I can think of is to put the user info in a hidden field in HTML and access it like that, but that sounds messy and not proper.
This is my first time posting here so I apologize if it was too lengthy or not specific enough. Thanks!
The answer was in the way I was declaring passport and stripe in my application. Make sure you declare passport after everything to make the user variable available to stripe and all views.