将ExpressJS称为HTML页面的Rest API

时间:2022-10-16 13:27:08

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

我正在创建一个带有按钮的网页,通过ExpressJS,NodeJs使用Rest API构建从服务器加载数据。

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

此应用程序的HTML页面如下所示

<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.

当我在浏览器中运行http:// localhost:3000 / search时,它会从数据库中输出“name”。但是,如何查看index.html页面并在按钮单击时加载它。

5 个解决方案

#1


8  

Update:

更新:

OP Asks:

OP问:

"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"

“我的问题不是代码说的......我的问题是如何更改代码,以便表达式作为RESTful API而不是渲染引擎”

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).

要在此处使用express作为RESTful API,首先需要提供静态页面。换句话说,这里是以下步骤:1。让您的快速服务器提供静态页面。 2.然后获取该页面上的按钮,在/ search(点击时)向api端点发出GET请求。

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!

在我的答案的第二部分解释了1。 2应该已经可以工作,你只需要提供页面并单击按钮!

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.

当我在浏览器中运行http:// localhost:3000 / search时,它会从数据库中输出“name”。

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!".

这意味着每当GET请求进入您的路由时(在本例中,localhost:3000上的路径/搜索),就会执行回调函数。基本上,当你访问localhost:3000 / search时,你的浏览器发送一个GET请求,Express检查*与每条路由匹配的请求,最后“好吧,那是我需要响应的GET请求,让我们开始搜索! ”。

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

但是,如何查看index.html页面并在按钮单击时加载它

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).

它可能无法正常工作,具体取决于您的html的定义位置以及您的名称。记得发送正确的文件。一个更简单的推理方法就是让表达式知道你正在提供静态HTML。**这可以通过app.use(“/”,express.static(__ dirname))完成;但同样,请确保上面定义的html位于正确的根文件夹(可能名为server或类似的东西)中的文件中,名称为index.html(并且只有其中一个)。

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

(请参阅底部有关表达中间件如何工作以及提供静态HTML的链接)

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).

总结一下,您首先要实现此答案的后半部分,以便您可以直接转到localhost:3000来加载索引页面。该页面将有一个按钮。然后,您将能够单击该按钮并向您的/搜索路线发出请求,而无需重定向。名称的内容现在应该回到浏览器(而不是作为新页面)。

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

*有关如何在此处检查/处理请求的更多信息。 **有关提供静态HTML的更多信息。这篇关于快速基础知识的博客也可能有用。

#2


1  

1-You have to add routing for index.html

1 - 您必须为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

然后在你的ajax代码中,你可以使用window.location重定向到/ index

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

2-你可以直接渲染index.html。像这样的东西

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.

然后在单击按钮时重定向到页面/索引。

#3


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.

您遇到的问题是您使用Express作为渲染帧工作。如果要使用REST / API构建应用程序,则框架不应呈现视图或模板。网页导航应该是分开的(例如Angular JS)。在您的情况下,当您调用/搜索时,实际上只是在服务器中调用某些内容而没有任何渲染指令。这就是为什么你看到一个响应JSON对象而不是你的html模板。

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..

那么,该怎么做?..你需要在你的客户端制作一个导航应用程序,只需浏览模板,没有任何异常,并编程你的按钮来对某些api url做一个请求(类似于:localhost:3000 / api / search)和响应的内容做一些事情:比如填表,以某种方式显示它们或其他什么..

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

我建议你尝试一下Angular JS。我相信它可以帮到你

Cheers

干杯

#4


-1  

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

这是我在使用简单的index.html页面测试一些前端代码时使用的代码。

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.

这会将根路径映射到index.html。 __dirname假定index.html文件与express的初始服务器/ app文件位于同一目录中。如果你想使它更通用,你可以做类似下面的事情但是你需要手动将index.html添加到浏览器的地址栏,但它也允许你加载你想要的任何其他静态文件。

app.get(/^(.+)$/, function(req, res){
  res.sendFile( __dirname + req.params[0]);
});

#5


-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/

你可以从jquery api文档http://api.jquery.com/jQuery.ajax/阅读有关$ .ajax()的文档。

#1


8  

Update:

更新:

OP Asks:

OP问:

"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"

“我的问题不是代码说的......我的问题是如何更改代码,以便表达式作为RESTful API而不是渲染引擎”

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).

要在此处使用express作为RESTful API,首先需要提供静态页面。换句话说,这里是以下步骤:1。让您的快速服务器提供静态页面。 2.然后获取该页面上的按钮,在/ search(点击时)向api端点发出GET请求。

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!

在我的答案的第二部分解释了1。 2应该已经可以工作,你只需要提供页面并单击按钮!

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.

当我在浏览器中运行http:// localhost:3000 / search时,它会从数据库中输出“name”。

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!".

这意味着每当GET请求进入您的路由时(在本例中,localhost:3000上的路径/搜索),就会执行回调函数。基本上,当你访问localhost:3000 / search时,你的浏览器发送一个GET请求,Express检查*与每条路由匹配的请求,最后“好吧,那是我需要响应的GET请求,让我们开始搜索! ”。

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

但是,如何查看index.html页面并在按钮单击时加载它

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).

它可能无法正常工作,具体取决于您的html的定义位置以及您的名称。记得发送正确的文件。一个更简单的推理方法就是让表达式知道你正在提供静态HTML。**这可以通过app.use(“/”,express.static(__ dirname))完成;但同样,请确保上面定义的html位于正确的根文件夹(可能名为server或类似的东西)中的文件中,名称为index.html(并且只有其中一个)。

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

(请参阅底部有关表达中间件如何工作以及提供静态HTML的链接)

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).

总结一下,您首先要实现此答案的后半部分,以便您可以直接转到localhost:3000来加载索引页面。该页面将有一个按钮。然后,您将能够单击该按钮并向您的/搜索路线发出请求,而无需重定向。名称的内容现在应该回到浏览器(而不是作为新页面)。

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

*有关如何在此处检查/处理请求的更多信息。 **有关提供静态HTML的更多信息。这篇关于快速基础知识的博客也可能有用。

#2


1  

1-You have to add routing for index.html

1 - 您必须为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

然后在你的ajax代码中,你可以使用window.location重定向到/ index

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

2-你可以直接渲染index.html。像这样的东西

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.

然后在单击按钮时重定向到页面/索引。

#3


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.

您遇到的问题是您使用Express作为渲染帧工作。如果要使用REST / API构建应用程序,则框架不应呈现视图或模板。网页导航应该是分开的(例如Angular JS)。在您的情况下,当您调用/搜索时,实际上只是在服务器中调用某些内容而没有任何渲染指令。这就是为什么你看到一个响应JSON对象而不是你的html模板。

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..

那么,该怎么做?..你需要在你的客户端制作一个导航应用程序,只需浏览模板,没有任何异常,并编程你的按钮来对某些api url做一个请求(类似于:localhost:3000 / api / search)和响应的内容做一些事情:比如填表,以某种方式显示它们或其他什么..

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

我建议你尝试一下Angular JS。我相信它可以帮到你

Cheers

干杯

#4


-1  

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

这是我在使用简单的index.html页面测试一些前端代码时使用的代码。

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.

这会将根路径映射到index.html。 __dirname假定index.html文件与express的初始服务器/ app文件位于同一目录中。如果你想使它更通用,你可以做类似下面的事情但是你需要手动将index.html添加到浏览器的地址栏,但它也允许你加载你想要的任何其他静态文件。

app.get(/^(.+)$/, function(req, res){
  res.sendFile( __dirname + req.params[0]);
});

#5


-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/

你可以从jquery api文档http://api.jquery.com/jQuery.ajax/阅读有关$ .ajax()的文档。