8

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.

KlwntSingh
  • 1,084
  • 8
  • 26
ghost...
  • 975
  • 3
  • 16
  • 33
  • 2
    I think you might want to load html file using express, for that you can use express serve static https://github.com/expressjs/serve-static – progrrammer May 25 '15 at 11:47

5 Answers5

8

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.

Community
  • 1
  • 1
Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20
  • 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 – ghost... May 28 '15 at 08:22
  • Hello! I feel like I answered that question (by explaining how you can serve a static page, and *use that page to perform your search*, thus using express as a RESTful api). My answer responds to your questions at the bottom..."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." Can you please try reading again and explain what you don't understand? I will try to reword my answer. Thanks! – Sze-Hung Daniel Tsui May 28 '15 at 21:13
  • 1
    Updated. I hope that helps! – Sze-Hung Daniel Tsui May 28 '15 at 21:19
  • Actually i was just looking for app.use("/", express.static(__dirname)); But thanks for explain things to me. – ghost... Jun 04 '15 at 04:56
  • Cool! [This question](http://stackoverflow.com/questions/18165138/res-sendfile-doesnt-serve-javascripts-well) ends up being similar to what you were asking. Check it out if you have other questions, or want to serve up files in a nested file structure. – Sze-Hung Daniel Tsui Jun 06 '15 at 15:03
1

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.

PPB
  • 2,937
  • 3
  • 17
  • 12
  • I don't want to render through express. Just restful api call through express. Like in C#, we have say index.html page running on a server and we use ajax to call webservices(asmx or svc) file method..... – ghost... May 28 '15 at 17:27
  • @ghost... Then you have to use SPA frameworks like AngularJs,BackBone ReactJs etc. – PPB May 29 '15 at 06:55
  • I can use angular but not sure how to run those file as i get cross domain issue – ghost... May 29 '15 at 06:55
  • 1
    Try an AngularJs tutorial.then soon you will fine what is going wrong and what is the right way. http://adrianmejia.com/blog/2014/09/28/angularjs-tutorial-for-beginners-with-nodejs-expressjs-and-mongodb/ – PPB May 29 '15 at 07:03
0

The problem you have is that you are using Express as a render FrameWork. If you want to build an app with REST/API, the framework should not render the views or templates. The webpage navigation should be separate (e.g Angular JS). In your case, when you call /search you are actually only calling something in the server without any rendering instruction. That is why you see a response JSON object instead of your html template.

So, what to do?.. You need to make a navigation app on your client side, just navigating through templates with nothing out of normal, and program your button to do its request to some api url (something like: localhost:3000/api/search) and with the contents of the response do something: like filling a table, showing them somehow or whatever..

I recommend you to give a try to Angular JS. I am sure it can help you

Cheers

Cesar Villasana
  • 681
  • 3
  • 6
  • i created index file using simple angular and html...how to run index file....if i run it http://localhost:3000/index it says cannot get index....if i run on xampp or wampp calling...hitting the button says cross domian issue as the port number are different for apache and expressjs server – ghost... May 26 '15 at 01:54
  • U are still confused on how to render something locally. Which is definetly not calling localhost:3000/index -> This is calling a server not a local index file.. – Cesar Villasana May 26 '15 at 18:25
  • I am confused that's why I asked this question....rendering local index page and calling restful api to it on some event – ghost... May 27 '15 at 05:09
  • 1
    OP isn't asking how to do this with Angular. Based on the snippet he post, he can totally do this without learning a new framework.. – Sze-Hung Daniel Tsui May 28 '15 at 05:12
-1

Here is the code I use when I am wanting to use a simple index.html page for test some front-end code.

app.get("/", function(req, res) {
  res.sendFile( __dirname + '/index.html')
});

This will map the root path to your index.html. The __dirname assumes the index.html file is in the same directory as your initial server/app file for express. If you want to make it more generic you can do something like the following but then you will need to manually add the index.html to the address bar in your browser but it also lets you load any other static files you want.

app.get(/^(.+)$/, function(req, res){
  res.sendFile( __dirname + req.params[0]);
});
Jedediah Smith
  • 558
  • 4
  • 10
-1
<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(data) {
            $('div').append(data);  
        });
    });
});
</script>

you can read the documentation about $.ajax() from jquery api documentation http://api.jquery.com/jQuery.ajax/

HDK
  • 816
  • 1
  • 8
  • 13