Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call ExpressJS as Rest API for HTML page

I am creating web page with a button to load data from the server using Rest API build through ExpressJS, NodeJs.

var express=require('express');
var mysql=require('mysql');
var app=express();
var server=app.listen(3000,function(){
	console.log("Express is running on port 3000");
});

app.get('/search',function(req,res){
	var mysql=require('mysql');
	var connection = mysql.createConnection({
		connectionLimit : 100, //important
		host     : 'localhost',
		user     : 'root',
		password : '',
		database : 'node-test'
	});
	connection.connect();
	connection.query('SELECT name from users', function(err, rows, fields) {
		if (err) throw err;
		var data=[];
		for(i=0;i<rows.length;i++){
			data.push(rows[i].name);
		}
		res.end(JSON.stringify(data));
	});
});

HTML page for this application looks like below

<button >Load from server</button>
<div></div>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $(document).on('click','button', function(){
		$.ajax({
		  url: "http://localhost:3000/search"
		}).done(function() {
			$('div').append("done !!! - ");
		});
	});
});
</script>

When I run http://localhost:3000/search in browser it gives me output with "name" from the database. But how can I see the index.html page and make it load on button click.

like image 352
ghost... Avatar asked May 25 '15 10:05

ghost...


People also ask

Does REST API support HTML?

REST API ResponseThe response payload can be whatever is practical: data, HTML, an image, an audio file, and so on. Data responses are typically JSON-encoded, but XML, CSV, simple strings, or any other format can be used.

Can you use Express with HTML?

In this short tutorial, I am going to explain to you how to render HTML files in a custom NodeJS and ExpressJS Server. You don't need to install any extra modules to render an HTML file in Express. Just install express and you are good to go.

Does Express use REST API?

Restful API is very popular and commonly used to create APIs for web-based applications. Express is a back-end web application framework of node js, and with the help of express, we can create an API very easily.


2 Answers

Update:

OP Asks:

"my question is not what code say....my question is how to change the code so that expressjs works as RESTful API and not rendering engine"

In order to use express as a RESTful API here, you first need to serve up a static page.
Said another way, here are the steps:
1. Get your express server to serve up a static page. 2. Then get the button on that page to make a GET request to your api endpoint at /search (when clicked).

1 is explained in the 2nd part of my answer.
2 should already work, you just need to serve the page and click the button!

I explain why this doesn't work in the first part of my answer. You can't simply navigate to /search. I think that is what you mean by "not use it as a render engine".


Original Answer:

To understand what is happening here, it might be a good idea to look at how you're handling requests in your serverside code:

When I run http://localhost:3000/search in browser it gives me output with "name" from the database.

That code is:

app.get('/search',function(req,res){
    var mysql=require('mysql');
    var connection = mysql.createConnection({
        connectionLimit : 100, //important
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'node-test'
    });
    connection.connect();
    connection.query('SELECT name from users', function(err, rows, fields) {
        if (err) throw err;
        var data=[];
        for(i=0;i<rows.length;i++){
            data.push(rows[i].name);
        }
        res.end(JSON.stringify(data));
    });
});

This means that whenever a GET request goes to your route (in this case, the path /search on localhost:3000), the callback function executes. Essentially, when you access localhost:3000/search, your browser sends a GET request, Express checks* the request for a match with each route, and finally going "ok, that's the GET request I need to respond to, let's start searching!".

So it's behaving as expected. Of course, that is not what you want...

But how can I see the index.html page and make it load on button click

Try something like this:

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});

It might not work as is, depending on where your html is defined and what you've named it. Remember to send the right file. A simpler way to reason about this would be to let express know you're serving up static html.** That could be done with
app.use("/", express.static(__dirname)); But again, make sure the html defined above is in a file in the proper root folder (probably named server or something similar), with the name index.html (and that there is only one of them).

(See the links on how express middleware works, and serving static HTML, at the bottom)

To wrap up, you implement the second half this answer first, so that you can go directly to localhost:3000 to load your index page. That page will have a button. Then, you'll be able to click the button and make a request to your /search route, without redirecting. The contents of name should come back to the browser now (instead of being served as a new page).

*More on how requests get checked/processed here.
**More info on serving static html. This blog on express fundamentals may also be useful.

like image 89
Sze-Hung Daniel Tsui Avatar answered Sep 29 '22 06:09

Sze-Hung Daniel Tsui


1-You have to add routing for index.html

app.get("/index", function(req, res) {
  res.render(index.html);
});

And then in your ajax code you can redirect to /index using window.location

2- you can directly render index.html. Something like this

app.get("/search", function(req, res) {
      res.render(search.html,{});
    });


app.get('/index',function(req,res){
var mysql=require('mysql');
var connection = mysql.createConnection({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'node-test'
});
connection.connect();
connection.query('SELECT name from users', function(err, rows, fields) {
    if (err) throw err;
    var data=[];
    for(i=0;i<rows.length;i++){
        data.push(rows[i].name);
    }
    res.render(index.html,{data:data});
});

});

then redirect to page on /index when clicking button.

like image 34
PPB Avatar answered Sep 29 '22 05:09

PPB