How should I go about parsing and using website data? I am using node js [closed] - html

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am using node js to create a bot that gets stats from r6.tracker.network, but when I load it in the data won't show up unlike when I have 'www.google.com' as the host. I don't really know where to go from here. I'm trying to use several different debugging methods, but I haven't found anything yet. There is no output.
function getWebpage(parameter){
const pathuser = '/profile/pc/' + parameter;
var http = require('http');
var options = {
host: 'r6.tracker.network',
path: '/'
}
var request = http.request(options, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
console.log(data);
});
});
request.on('error', function (e) {
console.log(e.message);
});
request.end();
}

They are redirecting you to the https version of their site.
The key here is to add this logging:
console.log(res.statusCode);
console.log(res.headers.location);
When you do that, you will see this:
301
https://r6.tracker.network/
In other words, they want you to use the https version of their site and they are redirecting you to do that. You won't get the content of the web page from the http URL. You have to use https.
Coding takeaways here:
Always look at the http status and only proceed normally if you get a 2xx response.
Be prepared for 3xx redirect responses.
FYI, if you use a more modern library such as got() or any of the other libraries listed here, they will all follow redirects for you automatically and they will gather the full response for you automatically too. And, they use the more modern promise-based method of asynchronous programming. I'd really suggest you pick one of those libraries for your outbound http requests.

Related

Where to specify whether it's a GET or POST?

When I create a new Google Cloud function, the default code given is:
const functions = require('#google-cloud/functions-framework');
functions.http('helloHttp', (req, res) => {
res.send(`Hello ${req.query.name || req.body.name || 'World'}!`);
});
However, in this tutorial, the function is specified as:
exports.validateTemperature = async (req, res) => {
try {
if (req.body.temp < 100) {
res.status(200).send("Temperature OK");
} else {
res.status(200).send("Too hot");
}
} catch (error) {
//return an error
console.log("got error: ", error);
res.status(500).send(error);
}
};
What is the difference between the two? How do they work in the bigger scheme of things?
In the second example, the code is listening for a Http POST request. Where is this specified?
Through the two methods you exposed the result is the same, a HTTP Path is used to receive the Request and Response objects.
Inside the Request object, you may find the Body (usually filled in POST & PUT requests but not limited to) and the Method (GET, POST, PUT, etc).
Therefore, your Cloud Function code will be used with both a GET and a POST call in either solution.
Functions Framework
Functions Framework turns a Cloud Functions snippet into a workable server. It's kind of like register a handler function to an express router, and run the express app behind the scenes.
The main use case is local development and migrant to App Engine or other services. They both need to start a HTTP server, and functions framework does that.
Express
Node.js runtime explains your code snippet using Express framework.
The validateTemperature accepts all HTTP methods.
We often filter HTTP methods by a router. Although you can do it in with req.method. And router, web server level is what you don't want to reapeat again and again.
If you want to split requests by method when buiding an API service, you could consider let Cloud Endpoints or some API Gateway stands before your functions.

Returning JSON through angular and bible.org api or esvapi.org

I've been researching this and cannot find or understand some of the solutions so i'm hoping to get some help here. I'm using Asp.net and building an application that needs to use a bible api. I like the two listed in the question. Every time I call esvapi it comes back successful, but I cannot view the data. I get an error in the console.
XMLHttpRequest cannot load http://www.esvapi.org/v2/rest`/passageQuery?key=8834092f0c58fcda&passage=James2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:59324' is therefore not allowed access.`
I've seen other with this error and I have questions.
If I'm understanding this correct I get this because the server is preventing me from seeing the data for security purposes. Maybe even the browser( this is not just a chrome issue) problem. So if I need to add a info to the response header from Angularjs to stop this how is that done. Anyone with experience?
Would I need to contact anyone to be able to prevent the server from responding this way...I doubt this, but thought I would ask. I already have valid api key.
the bible.org website api key is confusing to apply to my code. on esvapi i just add a header with key: "keypass" and I only have the CORS issue. But with bible.org I can't figure out how to implement the api key and password. see below... Do I say token:key: username. If i put the api in the browser I get a popup to add username and password. the username is my key and the password is ignored. I tried putting in username as key, but that didn't cut it. Regardless I need to fix the CORS issue and add info to response headers to see response data.
$scope.search = function() {
return $http.get("http://www.esvapi.org/v2/rest/passageQuery?&passage=" + $scope.bo + $scope.chap, {
headers: {
"key?token?orusername?": "",
///thought i saw someone do this...don't know if this is right
"Access-Control-Expose-Headers": "Content-Disposition",
}
}).success(function (data, status, headers, config) {
$scope.book = data.Book;
$scope.chapter = data.Chapter;
$scope.output = data.Output;
}).error(function (data, status, headers, config) {
$scope.message = "Oops... something went wrong";
});
Any input would be helpful. Thanks!
I actually have a bible api working...just a version that I don't like and there is not another version on that webites api.
Change the get $http.get call to $http.jsonp and hope it works. You're using cross-site scripting. Sometimes you can get away with a JSONP call in these cases and sometimes you can't.

Import JSON document array / object to a Meteor Collection with correct _ids [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the best way to import a 15,000 document json file of a format (but with a +30 foo fields)
[{"foo1":"foo1data1", "foo2":"foo2data1"}, {"foo1":"foo1data2", "foo2":"foo2data2"}...
{"foo1":"foo1dataN", "foo2":"foo2dataN"}])
to a Meteor collection?
I tried with mongoimport but that created ObjectID's instead of _id's and I could not make it work without autopublish, although other collections, created with Meteor, work just fine on client side.
Supposing the file is located on the server under pathToFile you can do something like this:
var fs = Npm.require("fs");
var Fiber = Npm.require("fibers");
fs.readFile(pathToFile, 'utf8', function (err, data) {
// handle error if there is some
data = JSON.parse(data);
Fiber(function () {
_.each(data, function (document) {
SomeMeteorCollection.insert(document);
});
}).run();
});
Please note that Fiber wrapper is required if you want call any meteor specific routines, for example collections API, within some nodejs asynchronous code.

Beginner JSON/JQuery Issue

I'm building a Django application and am trying to integrate JSON, but I'm having some issues. Django is generating the feed, which is here: http://www.crowdpoint.org/session/1/activeCheck
Here is the JQuery I'm using to pull down the feed. The problem is that neither of the alerts fire, so I don't think the code is working.
$(document).ready(function() {
$.getJSON('http://www.crowdpoint.org/session/1/activeCheck', function(data) {
alert('Test 1')
$.each(data, function(key, val) {
alert('Test 2');
});
});
It's probably a same origin policy violation. If the JS and the JSON resource are on the same domain, you should be using a local path not a fully qualified URI. For example...
instead of this
$.getJSON('http://www.crowdpoint.org/session/1/activeCheck' ...
use this
$.getJSON('/session/1/activeCheck' ...
My guess is you're accessing the originating URL on http://crowdpoint.org/ or something else that isn't exactly http://www.crowdpoint.org/
If the script and resource are on different domains, you'll need to use JSONP which would involve some changes to the way your service responds.
you miss ; in the third line....

Calling json function in wordpress

In my wordpress plugin I need to have a JSON option to load, using jquery, info about a custom post type. This jquery call will come in a page where all users should see it.
as far as i understand from the codex I should have a function:
function my_json_returning_function(){
// get json objects here
echo $json;
die();
}
As well as the actions:
add_action('wp_ajax_my_json_action', 'my_json_returning_function');
add_action('wp_ajax_nopriv_my_json_action', 'my_json_returning_function');
All in my plugin file.
then something like:
jQuery(document).ready(function($) {
var data = {
action: 'my_json_action',
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(<?php echo admin_url('admin-ajax.php');?>, data, function(response) {
alert('Got this from the server: ' + response);
});
});
should call the function in question.
My real question is where i should place all the different parts - and if something is missing.
The php function and the actions hooks go into the plugin file. But the javascript I am more confused about. I want to put it in the plugin javascript file, but since i have to fetch the admin url using php that becomes a problem.
Also how do I make sure that the script is only called if in a certain page? Are there more hooks and filters I should be comfortable with? Or is it possible to load it using wp_enqueue_script when executing a shortcode on that page, or is that to late, as I would seem it needs to be loaded in the header.
A lot of questions, but I hope you understand the basis of my problem - I have a hard time placing the code in the right places in the wordpress structure.
EDIT:
Calling echo admin_url('admin-ajax.php'); is not, at least in my eyes the most elegant way of doing it. I'd rather have a json API, with its seperate url, and calling it in the ajax call. How would I go about setting up a page in wordpress that only returns a json object?
What you have above is partially correct.
when using the call to admin-ajax.php, you have in the comments from the wordpress codex page is
// since 2.8 ajaxurl is always defined in the admin header
// and points to admin-ajax.php
this is just it... use the javascript variable 'ajaxurl' in place of the php call..
so it would look like this
jQuery(document).ready(function($) {
var data = {
action: 'my_json_action',
};
// since 2.8 ajaxurl
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
that should be you.. just place all your functions inside your main plugin file.
when wordpress loads it will produce a variable called ajaxurl that you can then use in your scripts.. :)