using file scope variables in node.js - javascript

Beginner question
Running on server side, in node.js:
If I use a file-scope (or even global) variable which is set by an export.function(), where that exported function is called via ajax from a client, if multiple requests come from different clients, is the variable now prone to unexpected results?
I.e. do I need to set up an array so every time the export.function() is called it adds a new file-scope instance for that particular ajax request? Or is this magically handled by node.js where every ajax request gets its own instance of the server?

Requests will share the same instances so you'll need to guard against this. Note, however, that blocks of synchronous code will be executed completely before execution switches to handle another request so this simplifies the "guarding" you need to do.

Related

how to access request or response objects in express.Js anywhere?

in an express.Js app ;i want to write a controller class that handles the request & response for other controllers for example add data to locals in res object or delete data from req.session etc.
is there a way i can do it without passing req or res as an argument
can i access them globally
The correct and possible way is to pass the req object as an argument to functions that need to use it.
Placing it in global variables will not work because multiple requests can be processed at the same time if for example requests use some asynchronous calls as part of their processing. So, multiple requests will stomp on other requests and will make it really hard to track down bug.
node.js is a server that can potentially handle many requests for many clients. Server may have many requests all in flight at the same time and thus plain globals you wish to use cannot be used for request-specific data.

How can I exchange data between nodejs and puppeteer?

I made a nodejs application that starts from index.js.
Then, index.js launches puppeteer and injects bot.js on a headless-api page by addscripttag function.
I made index.js sets a cookie for conveying initial values before injecting javascript, but I need more common way to exchange data.
I thought two ways; the first is using cookie, and the second is networking via socket connection.
Is there other way for send and receive data between index.js(node) and puppeteer(headless chrome)?
First, puppeteer IS nodejs side application, so they have a single environment and you don't need to "send" anything. Just pass data around as you'd do in any other JS code. I assume you want to transfer data between page and nodejs then.
To pass data from nodejs to page use page.evaluate. You can call any code in page context, ranging from simply setting some variables to directly calling whatever functions with necessary arguments.
To initiate transfer from page side to nodejs, first register a nodejs-side callback function with page.exposeFunction and then call it from page code and it will be executed in nodejs context. Just like in previous case, everything else depends on code of that function. It can be as simple as storing whatever argument you pass to it in some variable or directly perform with data pretty much whatever you want.

is it possible to execute any php function using ajax [duplicate]

So far when creating AJAX requests I have been posting to a separate PHP file. Is it possible to create a jQuery AJAX request that calls a PHP function rather than posts to a separate page?
If you could send me any examples or documentation would be great.
I believe there's a fundamental misunderstanding of how the technology works here.
AJAX (Javascript), Flash, or any client-sided technology cannot directly call PHP functions (or other languages running on the server).
This is true for going the other way around as well (eg: PHP can't call JS functions).
Client and server codes reside on different machines, and they communicate through the HTTP protocol (or what have you). HTTP works roughly like this:
Client (eg: browser) sends a REQUEST -> Server processes request and sends a RESPONSE -> Client gets and displays and/or processes the response
You have to see these requests and responses as messages. Messages cannot call functions on a server-side language directly 1, but can furnish enough information for them to do so and get a meaningful message back from the server.
So you could have a handler that processes and dispatches these requests, like so:
// ajax_handler.php
switch ($_POST['action']) {
case 'post_comment':
post_comment($_POST['content']);
break;
case '....':
some_function();
break;
default:
output_error('invalid request');
break;
}
Then just have your client post requests to this centralized handler with the correct parameters. Then the handler decides what functions to call on the server side, and finally it sends a response back to the client.
1 Technically there are remote procedure calls (RPCs), but these can get messy.
AJAX requests call a URL (make a HTTP request), not a file, in most cases the URL is translated by the server to point at a file (or a php script in your case), but everything that happens from the HTTP request to the response that is received is up to you (on your server).
There are many PHP frameworks that map URL's to specific php functions, AJAX is just an asynchronous way to access a URL and receive a response.
Said URL CAN trigger the server to call a specific function and send back a response. But it is up to you to structure your URL's and server side code as such.
If you're asking whether you can call any arbitrary PHP function with AJAX the answer is no*, for obvious security reasons (in addition to the technical reasons). You could make a PHP script that does different things depending on what parameter it's given (for example, execute a single function) if you don't want to create multiple separate files.
*Although you could make a script that would execute any arbitrary PHP command coming from the client, but that would be very, very, very unwise.
Short answer is "no" but the real answer is that you can fake it. NullUserException's answer is good. You create a server that will take the function name and its parameters. Then the server executes the function, and returns the value.
This was done a while back via a protocol called XML-RPC. There was also an effort called JSON-RPC that used some JS techniques.
One things that's cool about JS is that you can do things like this:
var base64_decode = create_remote_call('base64_decode');
function create_remote_call(name) {
return function(x) {
jQuery.getJSON('url/server.php',
{func:name,arg:x},
function(d){return d;});
}
}
A call to base64_decode('sarefdsfsaes') will make a ajax request and return the value.
That code probably won't work because it hasn't been tested, but it's a function that produces a function that will call the server, and then return the value. Handling more than one argument requires more work.
All that said... in my experience, it's usually good to make all network communications explicit instead of disguising it as a regular function.
you may achieve the same result using a bridge, like my phery library http://phery-php-ajax.net you can call PHP functions directly from Javascript and deal with the value. The AJAX is bound to DOM elements, so you can manipulate the calling DOM or just use jQuery from the PHP side. An example would be:
Phery::instance()->set(array(
'phpfunction' => function(){
return PheryResponse::factory()->jquery('body')->addClass('whoops');
}
))->process();
and in the javascript side (or HTML)
phery.remote('phpfunction');
the equivalent to the https://stackoverflow.com/a/7016986/647380 from John Kawakami answer, using phery is:
function base64($data){
return !empty($data['encode']) ? base64_encode($data['content']) : base64_decode($data['content']);
}
Phery::instance()->set(array(
'base64' => 'base64'
))->process();
function base64(content, decode, output){
phery.remote('base64', {'content': content, 'encode': decode ? 1 : 0}, {'type':'text'}).done(output);
}
base64('asdf', false, function(data){
console.log(data); // or assign to some variable
});
since AJAX is asynchronous and you can't just return a value from the AJAX call, you need a callback, but this would suffice.

How to get a synchronuous result from an HTTP request in node.js

I am writing a node module as a wrapper around a Python module (to make that module available from node.js). This module works as a standalone script or as an HTTP server.
When getting data from that script/server my function needs to return a value and can't do something in a callback function. At least that's how I understand it.
(One possible client is a gitbook-plugin, and when that encounters a "block" it has to call the plugin->my-client-module and insert its return value into the generated HTML document.)
So either I'm seeing something wrong because I'm too new to Node.js (coming from Python) or I need a way to make the HTTP request synchronous.
With the standalone script I can easily do it using ChildProcess.spawnSync, but not in an HTTP request.
Well, I know people are always recommending to do things asynchronously in Node, so I'd also be happy about pointers how to achieve my goal that way. As said I expect clients of my module to pass me some data, pass that along to invoke the script or do a POST request on the server and return the processed data to the client.
You can achieve synchronous HTTP requests using web-workers.
Here is more info on this topic:
https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_Synchronous_HTTP_request_from_a_Worker
Edit:
You can make synchronous requests from Node.Js. The following module should help:
https://www.npmjs.com/package/sync-request

PHP/AJAX Requests: session_start(): Cannot send sesssion cache limiter - headers already sent

I have a problem which I can not find a solution to:
After a mouse keypress (onclick="") in my web application, I call a PHP function via AJAX request. This is nothing unusual. However, the PHP function needs to access some session variables. As I call the PHP function via HTML5 onclick and AJAX request, the webpage is already rendered, which probably means the headers have already been sent.
Probably, as a result of that, I get the following error:
session_start(): Cannot send session cache limiter - headers already sent
The key information here is that my PHP function called through AJAX Request does not output anything to the browser before calling session_start().
Is there any solution to this, please? Originally, I thought, AJAX function calls are independent from rendering the webpage and I could basically call session_start() at any time via AJAX. But now, it looks to me, that I can not call session_start() from my PHP function if called with AJAX request, just because all the AJAX calls are performed after rendering the webpage and thus after sending the headers?
Client Side: HTML5, JavaScript (no jquery)
Server Side: PHP, MySQL
If you have any idea for a workaround, that would help. Because of security reasons, I do not want to pass needed parameters as POST arguments. Because of speed reasons, I do not want to access them from my MySQL database. I would really like to know, if there is a way to access session variables through AJAX calls.
What I would like to know, if it is possible to replace AJAX calls with local PHP function calls. Then, I could take advantage of PHP global variables.
Thank you.

Categories

Resources