node.js jquery - .post ajax like php - node.js

I am coming from PHP where an AJAX call from jQuery is done like this.
html:
$('a').click(function(){
var mydata = 'abc123';
$.post( 'process.php', { mydata:mydata}, function(data){
$('body').append('<h1>'+data+'</h1>');
});
return false;
});
php:
$post = $_POST['mydata'];
echo $post;
Question: how can i replace the PHP part with node.js to do the same thing?
also i would need to change this part of jQuery $.post( 'process.php', ...
would that look like this? $.post( 'process.js', ...?
I saw this post but i couldnt translate it from php to node
This helped out, from "Node.js for PHP developers"
In PHP, a PHP file represents an HTML page. A web server, such as Apache, accepts
requests and if a PHP page is requested, the web server runs the PHP. But in Node.js,
the main Node.js file represents the entire web server. It does not run inside a web server
like Apache; it replaces Apache.

Related

Serving CSS stylesheets that are linked to HTML files via the link tag in Node.js w/o a framework

I have been teaching myself Node.js by way of trial & error. I built a simple server using the Node.js HTTP class. I figured out that I can read a file asynchronously and serve the data using the asynchronous fs.readFile(..., cbk) callback method. What I don't understand at this point is how respond with all the other resources that the requests needs.
// "./index.js"
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('index.html', function(err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
For the sake of maintaining a single focus, I will use only Style-sheets as an example. Below is a super common link tag that demonstrates how I typically tell the server that the pages needs a specific CSS file. It works fine on the front-end side of things. But, how to I handle a request from a link tag on the the server's side of things (or on the backend)?
<link rel="stylesheet" type="text/css" href="/foo/bar/raboof.css">
Note: This is just a test project, but it doesn't use any frameworks, or even any modules (except for the dev-mod eslint). I would perfer to do this without 3rd party software/tools/frameworks etc...
Your nodejs server is not programmed to send any style sheets when the browser requests them.
A nodejs server, like you've created, serves NO files by default. It only serves files that you program it to serve. So, your nodejs server is programmed to do one thing and one thing only and that's to deliver index.html no matter what URL is requested from it.
So, here's what happens:
User enters some URL for your site
Browser sends your server a request for that page
Your web server delivers index.html
Browser parses index.html and finds style sheet links
Browser sends your server a request for a style sheet link
Your server sends it index.html
Browser realizes "that's not a style sheet" and you get no styles
So, for your HTML server to work properly, you have to add code to look at the requested URL and, if it's a style sheet URL, it needs to send the proper file for that stylesheet, not just blindly send index.html no matter what was requested.
Nobody says you need to use the Express library for this, but this is what it does. It makes it very easy to configure what gets sent when different types of requests are made. And, for requests of static resources like CSS files, it can even just be configured to automatically send them direct from the file system.
If you don't want to use Express for this, you don't have to, but then you will have to write your own code to serve the right data when different URLs are requested.
If you want to write your own code for this, you will have to create some sort of if/else or switch statement or table lookup that looks at req.url and then send the appropriate content that matches the requested URL. Then, when the browser requests your style sheet, you can actually send it the appropriate style sheet, not index.html. The same would be true for Javascript files, images, page icon, ajax requests or any resource on your server that your page references.
Because your server-side code is written to handle all.http requests and deliver the same html content, regardless of the path.
try adding some if-else logic inside your handler, and deliver appropriate file based on the request path.
something like:
if(req.path === "" || req.path === "index.html")
fs.read htnl file here
else if (req.path==="my.css")
fs.read css file
learn to use browser dev tools (F12), which shows you exactly which requests the browser is making, what it sends, what it gets back - amongst many other things.

Open browser popup on APIrequest nodejs express

I want to open a browser popup for client site on rest api request to nodejs backend.
I had tried
res.setHeader('Content-Type', 'text/html');
res.render('index', { title: 'Hey', message: 'Hello' });
But it still returning html codes as data to the client.
I also used window.open but window is not defined in server side
Is there anyway to make my backend redirect or render html form on api request!
the following image is how the client get response
If you want the browser change page/view, you need something like location.href = /yourview.html
If you want fill your popup with html built on the server, you need to get it using fetch or XMLHttpRequest or something built on top of them (for example axios, like you did) and then attach to the dom.
Once you got it, you can show the popup. But you are on the client side.
res.render return rendered html. http://expressjs.com/en/api.html#app.render

Can i use AJAX request to update the whole page like reqular http requests?

If i can update the whole page with AJAX when and why should i use regular http methods?
Can AJAX requests replace normal http methods?
i am using nodeJS expressJS
Yes, you can update the whole page using AJAX. Send request from user end and get back an JSON array from server containing all the information you want.
If you want to load data from .txt file or .html, then
$.ajax({ url: 'http://website/some'
, type: 'GET'
, dataType: 'html'
})
.done(function(data) {
$('#container').html(data);
})
.fail(function() {
console.log("Something went wrong!");
});
Just wondering why you are looking at AJAX when you need a complete reload.
Yes, definitely you can. But You will not ask this question once you know the use of AJAX.
For example, you will never ever update the whole page if you are using AJAX. For example, at least Navigation will remain the same and the body part will change. This is the use of AJAX and many web applications load like this. They keep navigation the same and then update rest of the web page.
You will have this kind of application where you will update the body of the page. You can use REST API to fetch the data in the form of JSON and then load this data using styling and Javascript framework like Angular, React, Backbone, etc.

Sending POST request to a Drupal module file

I'm trying to send a post request to a Drupal .module file from node.js. My problem is that the module file is never executed as php by Apache when the request is made, so instead of getting a response from php, I get the literal code (inside the .module file) as a text string.
I tried enabling .module to execute as php (not sure the security implications) by putting the following in .htaccess:
Addhandler application/x-httpd-php .module
(and virtually every other combination of that command I could find)
But no luck.
I know the post request sent by node.js is perfectly fine because it works when sent to .php files on the same server. I just can't get it to work within a Drupal module. I want it to be sent to a Drupal module because I want to take advantage of Drupal's API (going to be doing a lot of modifications to drupal user tables).
How do I send a post request to a drupal module, programmatically, from node and read its response? I know how to send it to a simple .php file, but not to a drupal module.
You create a menu in module file.
function mymodule_menu() {
$items['post-link'] = array(
'page callback' => 'mymodule_abc_view',
);
return $items;
}
and then send the post request on that menu link through Node.js.
YOURSITENAME/post-link?data1=abc&data2=def
And then fetch the post data on those menu call back function to use drupal_get_query_parameters() function.
function mymodule_abc_view() {
// ...
$parameters = drupal_get_query_parameters();
print "<pre>";
print_r($parameters);
print "</pre>";
}
it may be help for you.
Thanks,

nodejs mobile development: how control navigation flow

I am a nodejs newbie and would like to understand the navigation flow when using nodejs to serve mobile applications.
Moible app
index.html
Show all users
Nodejs server snippit
var myData = {
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
};
res.send(myData);
Question: how do I display this data on another page (users.html)? I've worked with nodejs where I can just render to a specific path and it picks the appropriate Jade file but not sure how to do it since the html / js files are on the phone and not the server.
If you know of an example application I can just look through that code and figure it out.
Thanks for your help.
First of all you need to understand that your node.js is executed on server side, and all it can do - response on requests and do some logic, that stays on the server.
Then there is .html and .js that is sent to your clients (browser), and it is rendered and executed on client-side. This execution and logic is very different, and is focused to provide user interactions and render all sorts of data.
So all you need is be able to 'ask' server for data (request) and then get response, validate it in browser, if it is valid, you can render it using JS.
In order to make your life easier, consider using jQuery.
AJAX - to make requests to server and get response with data.
express.js - web framework for node, helps with routes.
And just generally - go and try things, experiment and it is better to understand whole picture or specific details frist, before you making any decisions.

Resources