- 浏览: 31482 次
最新评论
#### 做前端开发,大多数情况下,都需要跟后端打交道,而最常见的方式则是通过http请求,进行通信。
在openresty中,通过http跟后端整合通信的方式又很多种,各有各的好处,可以根据情况交叉使用
## 1、直接proxy
这种方式最简单,也是我们最熟悉的,直接配置一个反向代理,跟nginx的用法一致
比如我们有一个后端服务,提供用户相关接口,是java写的,端口8080,为了简单起见,我直接在openresty里面配置一个server,模拟java端,通过一个简单的案例的来说明情况
nginx.conf
```
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
lua_package_path "/Users/john/opensource/openresty-web-dev/demo7/lua/?.lua;/usr/local/openresty/lualib/?.lua";
server {
listen 80;
server_name localhost;
lua_code_cache off;
location / {
root html;
index index.html;
}
location ~ ^/user {
proxy_pass http://127.0.0.1:8080;
}
}
# 这个只是模拟后端
server {
listen 8080;
server_name localhost;
lua_code_cache off;
location ~ /user/(.+) {
default_type text/html;
content_by_lua_file lua/$1.lua;
}
}
}
```
上面配置了两个location,将所有以/user开头的请求都转到后端的8080服务器,其他的则是静态页面,直接从html目录读取,然后返回,从这里开始就是前端开发了
为了简单起见,假设后端提供了一个登陆接口,我们这里直接用lua来实现一下就好了,检查用户名跟密码是admin,就返回成功,否则返回失败
lua/login.lua
```
local req = require "req"
local cjson = require "cjson"
local args = req.getArgs()
local username = args['username']
local password = args['password']
local res = {}
if username == "admin" and password == "admin" then
res['ret'] = true
res['token'] = ngx.md5('admin/' .. tostring(ngx.time()))
else
res['ret'] = false
end
ngx.say(cjson.encode(res))
```
index.html
```
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
UserName: <input type="text" id="username" value="admin">
Password: <input type="password" id="password" value="admin">
<a href="javascript:void(0)" onclick="login()">Login</a>
<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script>
function login() {
var username = $('#username').val();
var password = $('#password').val();
$.post('/user/login', {username: username, password: password}, function(res){
console.log(res)
var msg = res.ret ? "登录成功" : "登录失败"
alert(msg)
}, 'json')
}
</script>
</body>
</html>
```
2、使用ngx.location.captrue
这个方法主要用于发送内部请求,即请求当前server内的其他location,默认会将当前请求的参数带过去,也可以手动指定参数,GET参数通过args传递,post参数通过body传递
如:
local req = require "req"
local args = req.getArgs()
GET 调用
local res = ngx.location.capture('/user/login', {
method = ngx.HTTP_GET,
args = args,
});
POST 调用
local res = ngx.location.capture('/user/login', {
method = ngx.HTTP_POST,
body = ngx.encode_args(args),
});
现在我们自己写一个lua来调用后台接口实现登陆,然后对请求做一点处理,实现一些额外的逻辑,比如在原来的参数上面加上一个from字段
lua/local-login.lua
```
local req = require "req"
local cjson = require "cjson"
local args = req.getArgs()
-- GET
local res = ngx.location.capture('/user/login', {method = ngx.HTTP_GET, args = args})
-- POST
-- local res = ngx.location.capture('/user/login', {method = ngx.HTTP_POST, body = ngx.encode_args(args)})
-- print(res.status) -- 状态码
if res.status == 200 then
local ret = cjson.decode(res.body)
ret['from'] = 'local'
ngx.say(cjson.encode(ret))
else
print(res.body)
ngx.say('{"ret": false, "from": "local"}')
end
```
index.html 也需要改一下,多加一个按钮,调用本地登陆接口
```
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
UserName: <input type="text" id="username" value="admin">
Password: <input type="password" id="password" value="admin">
<a href="javascript:void(0)" onclick="login()">Login</a>
<a href="javascript:void(0)" onclick="local_login()">Local Login</a>
<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script>
function login() {
var username = $('#username').val();
var password = $('#password').val();
$.post('/user/login', {username: username, password: password}, function(res){
console.log(res)
var msg = res.ret ? "登录成功" : "登录失败"
alert(msg)
}, 'json')
}
function local_login() {
var username = $('#username').val();
var password = $('#password').val();
$.post('/lua/local-login', {username: username, password: password}, function(res){
console.log(res)
var msg = res.ret ? "本地登录成功" : "本地登录失败"
alert(msg)
}, 'json')
}
</script>
</body>
</html>
```
3、第三方模块[lua-resty-http](https://github.com/pintsized/lua-resty-http)
这种方式跟上面那种不同的地方是调用的时候,不会带上本地请求的请求头、cookie、以及请求参数,不过这也使得请求更纯粹,不会带上那些没必要的东西,减少数据传输
最后local-login.lua 变成如下
```
local req = require "req"
local cjson = require "cjson"
local http = require "resty.http"
local args = req.getArgs()
-- GET
-- local res = ngx.location.capture('/user/login', {method = ngx.HTTP_GET, args = args})
-- POST
-- local res = ngx.location.capture('/user/login', {method = ngx.HTTP_POST, body = ngx.encode_args(args)})
-- http
local httpc = http.new()
local res = httpc:request_uri("http://127.0.0.1:8080/user/login", {
method = "POST",
body = ngx.encode_args(args),
headers = {
["Accept"] = "application/json",
["Accept-Encoding"] = "utf-8",
["Cookie"] = ngx.req.get_headers()['Cookie'],
["Content-Type"] = "application/x-www-form-urlencoded",
}
})
httpc:set_keepalive(60)
print(res.status) -- 状态码
if res.status == 200 then
local ret = cjson.decode(res.body)
ret['from'] = 'local'
ngx.say(cjson.encode(ret))
else
print(res.body)
ngx.say('{"ret": false, "from": "local"}')
end
```
到此,基本上已经能通过openresty,做一些前后端的交互了,下次介绍怎么使用openresty模板渲染,以及搭配react开发前端。
[示例代码](https://github.com/362228416/openresty-web-dev) 参见demo7部分
在openresty中,通过http跟后端整合通信的方式又很多种,各有各的好处,可以根据情况交叉使用
## 1、直接proxy
这种方式最简单,也是我们最熟悉的,直接配置一个反向代理,跟nginx的用法一致
比如我们有一个后端服务,提供用户相关接口,是java写的,端口8080,为了简单起见,我直接在openresty里面配置一个server,模拟java端,通过一个简单的案例的来说明情况
nginx.conf
```
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
lua_package_path "/Users/john/opensource/openresty-web-dev/demo7/lua/?.lua;/usr/local/openresty/lualib/?.lua";
server {
listen 80;
server_name localhost;
lua_code_cache off;
location / {
root html;
index index.html;
}
location ~ ^/user {
proxy_pass http://127.0.0.1:8080;
}
}
# 这个只是模拟后端
server {
listen 8080;
server_name localhost;
lua_code_cache off;
location ~ /user/(.+) {
default_type text/html;
content_by_lua_file lua/$1.lua;
}
}
}
```
上面配置了两个location,将所有以/user开头的请求都转到后端的8080服务器,其他的则是静态页面,直接从html目录读取,然后返回,从这里开始就是前端开发了
为了简单起见,假设后端提供了一个登陆接口,我们这里直接用lua来实现一下就好了,检查用户名跟密码是admin,就返回成功,否则返回失败
lua/login.lua
```
local req = require "req"
local cjson = require "cjson"
local args = req.getArgs()
local username = args['username']
local password = args['password']
local res = {}
if username == "admin" and password == "admin" then
res['ret'] = true
res['token'] = ngx.md5('admin/' .. tostring(ngx.time()))
else
res['ret'] = false
end
ngx.say(cjson.encode(res))
```
index.html
```
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
UserName: <input type="text" id="username" value="admin">
Password: <input type="password" id="password" value="admin">
<a href="javascript:void(0)" onclick="login()">Login</a>
<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script>
function login() {
var username = $('#username').val();
var password = $('#password').val();
$.post('/user/login', {username: username, password: password}, function(res){
console.log(res)
var msg = res.ret ? "登录成功" : "登录失败"
alert(msg)
}, 'json')
}
</script>
</body>
</html>
```
2、使用ngx.location.captrue
这个方法主要用于发送内部请求,即请求当前server内的其他location,默认会将当前请求的参数带过去,也可以手动指定参数,GET参数通过args传递,post参数通过body传递
如:
local req = require "req"
local args = req.getArgs()
GET 调用
local res = ngx.location.capture('/user/login', {
method = ngx.HTTP_GET,
args = args,
});
POST 调用
local res = ngx.location.capture('/user/login', {
method = ngx.HTTP_POST,
body = ngx.encode_args(args),
});
现在我们自己写一个lua来调用后台接口实现登陆,然后对请求做一点处理,实现一些额外的逻辑,比如在原来的参数上面加上一个from字段
lua/local-login.lua
```
local req = require "req"
local cjson = require "cjson"
local args = req.getArgs()
-- GET
local res = ngx.location.capture('/user/login', {method = ngx.HTTP_GET, args = args})
-- POST
-- local res = ngx.location.capture('/user/login', {method = ngx.HTTP_POST, body = ngx.encode_args(args)})
-- print(res.status) -- 状态码
if res.status == 200 then
local ret = cjson.decode(res.body)
ret['from'] = 'local'
ngx.say(cjson.encode(ret))
else
print(res.body)
ngx.say('{"ret": false, "from": "local"}')
end
```
index.html 也需要改一下,多加一个按钮,调用本地登陆接口
```
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
UserName: <input type="text" id="username" value="admin">
Password: <input type="password" id="password" value="admin">
<a href="javascript:void(0)" onclick="login()">Login</a>
<a href="javascript:void(0)" onclick="local_login()">Local Login</a>
<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script>
function login() {
var username = $('#username').val();
var password = $('#password').val();
$.post('/user/login', {username: username, password: password}, function(res){
console.log(res)
var msg = res.ret ? "登录成功" : "登录失败"
alert(msg)
}, 'json')
}
function local_login() {
var username = $('#username').val();
var password = $('#password').val();
$.post('/lua/local-login', {username: username, password: password}, function(res){
console.log(res)
var msg = res.ret ? "本地登录成功" : "本地登录失败"
alert(msg)
}, 'json')
}
</script>
</body>
</html>
```
3、第三方模块[lua-resty-http](https://github.com/pintsized/lua-resty-http)
这种方式跟上面那种不同的地方是调用的时候,不会带上本地请求的请求头、cookie、以及请求参数,不过这也使得请求更纯粹,不会带上那些没必要的东西,减少数据传输
最后local-login.lua 变成如下
```
local req = require "req"
local cjson = require "cjson"
local http = require "resty.http"
local args = req.getArgs()
-- GET
-- local res = ngx.location.capture('/user/login', {method = ngx.HTTP_GET, args = args})
-- POST
-- local res = ngx.location.capture('/user/login', {method = ngx.HTTP_POST, body = ngx.encode_args(args)})
-- http
local httpc = http.new()
local res = httpc:request_uri("http://127.0.0.1:8080/user/login", {
method = "POST",
body = ngx.encode_args(args),
headers = {
["Accept"] = "application/json",
["Accept-Encoding"] = "utf-8",
["Cookie"] = ngx.req.get_headers()['Cookie'],
["Content-Type"] = "application/x-www-form-urlencoded",
}
})
httpc:set_keepalive(60)
print(res.status) -- 状态码
if res.status == 200 then
local ret = cjson.decode(res.body)
ret['from'] = 'local'
ngx.say(cjson.encode(ret))
else
print(res.body)
ngx.say('{"ret": false, "from": "local"}')
end
```
到此,基本上已经能通过openresty,做一些前后端的交互了,下次介绍怎么使用openresty模板渲染,以及搭配react开发前端。
[示例代码](https://github.com/362228416/openresty-web-dev) 参见demo7部分
发表评论
-
openresty 前端开发轻量级MVC框架封装二(渲染篇)
2017-01-11 00:50 1663#### 这一章主要介绍怎么使用模板,进行后端渲染,主要用到了 ... -
openresty 前端开发轻量级MVC框架封装一(控制器篇)
2017-01-10 22:48 747#### 通过前面几章,我们已经掌握了一些基本的开发知识,但是 ... -
openresty 前端开发入门六之调试篇
2017-01-04 14:03 771#### 大多数情况下,调试信息,都可以通过ngx.say打印 ... -
openresty 前端开发入门五之Mysql篇
2017-01-04 00:00 473openresty 前端开发入门五 ... -
openresty 前端开发入门四之Redis篇
2017-01-03 10:41 1441#### 这章主要演示怎么 ... -
openresty 前端开发入门三之JSON篇
2017-01-03 10:36 684#### 这章主要介绍一下,lua怎么返回一个json字符串, ... -
openresty 前端开发入门二
2017-01-03 10:36 523#### 这一章主要介绍介绍怎么获取请求参数,并且处理之后返回 ... -
openresty 前端开发入门一
2016-12-30 00:41 690OpenResty ™ 是一个基于 Nginx 与 Lua 的 ... -
使用nginx管理docker容器
2016-12-28 00:07 1564### 一直YY着想有一个基于web的docker管理器,市面 ... -
openresty 前端开发序
2016-12-09 11:45 456还记得第一次尝试前后端分离的时候,是使用nginx + ...
相关推荐
openresty 前端开发进阶三之后端整合二 openresty 前端开发进阶四之session篇 openresty 前端开发进阶六之websocket篇 openresty 前端开发高级应用一之性能优化 openresty 前端开发高级应用一之动态追踪技术 ...
OpenResty+Lua+Redis 高性能后端接口
OpenResty lua redis 实现
基于开源Litemall电商项目的大数据项目,包含前端埋点(openresty+lua)、后端埋点-litemall-dw
章亦春亲自书写的openresty官方学习资料,包含OpenResty 入门到精通、OpenResty 核心开发、OpenResty 在小语言下的开发。
OpenResty 是一个强大的 Web 应用服务器,Web 开发人员可以使用 Lua 脚本语言调动 Nginx 支持的各种 C 以及 Lua 模块,更主要的是在性能方面,OpenResty可以 快速构造出足以胜任 10K 以上并发连接响应的超高性能 Web ...
通过揉和众多设计良好的 Nginx 模块,OpenResty 有效地把 Nginx 服务器转变为一个强大的 Web 应用服务器,基于它开发人员可以使用 Lua 编程语言对 Nginx 核心以及现有的各种 Nginx C 模块进行脚本编程,构建出可以...
PGW(Proxy Gateway) Proxy Gateway基于openresty(nginx-lua-module)开发,可以作为接口网关(api gateway)使用,整合业务模块接口,微服务治理聚合,通过web配置界面,能够轻松进行代理配置管理,支持负载均衡...
OpenResty的目标是让你的Web服务直接跑在 Nginx 服务内部,充分利用 Nginx 的非阻塞 I/O 模型,不仅仅对 HTTP 客户端请求,甚至于对远程后端诸如 MySQL、PostgreSQL、Memcached 以及 Redis 等都进行一致的高性能响应...
OpenResty最佳实践是一本介绍lua语言在nginx应用中的书籍,对lua在nginx的工作原理进行实例说明,介绍编码,适合Web前端开发,网关开发,限流代理服务器开发等
OpenResty® 的目标是让你的Web服务直接跑在 Nginx 服务内部,充分利用 Nginx 的非阻塞 I/O 模型,不仅仅对 HTTP 客户端请求,甚至于对远程后端诸如 MySQL、PostgreSQL、Memcached 以及 Redis 等都进行一致的高性能...
luastar是一个基于openresty的高性能高并发开发框架,支持http接口和web开发。 luastar使用openresty-1.7.10.2在macOS和centos6.5系统上测试过。 luastar主要特性如下: request/response封装...
于是我一个人开始了OpenResty之旅,刚开始经历了各种技术挑战,庆幸有详细的文档,以及春哥和邮件列表里面热情的帮助,我成了团队里面bug最少和几乎不用加班的同学。 2014年,团队进来了一批新鲜血液,他们都很有...
OpenResty最佳实践,涵盖了多方面的知识,从LUA脚本作为切入点,到进阶的OpenResty学习
里面,也接触过 Nginx c 模块的高性能开发,一直想找到一个兼备 Python 快速开发和 Nginx c 模块高性能的产 品。看到 OpenResty 后,有发现新大陆的感觉。 于是我在新产品里面力推 OpenResty ,团队里面几乎没有人...
openresty_dev 这是OpenResty编程的示例代码。 要求 Linux或其他UNIX之类的 OpenResty 1.13.6.x或更高版本 链接 module-将Lua的功能嵌入Nginx module-将Lua的功能嵌入NGINX TCP服务器 也可以看看 -Nginx cpp开发...
这个openresty包是基于官方最新代码 编译好的。 openresty中升级nginx openresty如何升级nginx的版本? Nginx 有RCE 漏洞。 修复nginx 爆出栈溢出rce漏洞,openresty什么时候升级,或者如何单独升级nginx nginx内核...
idea+openresty+lua运行nginx服务器, 代码和软件都有, 参考资料: https://blog.csdn.net/dongyuxu342719/article/details/90413904
Nginx是当前最流行的HTTP Server之一,根据W3Techs的统计,目前世界排名(根据Alexa)前100万的网站中。与Apache相比。 同时,大量的第三方扩展模块也令Nginx越来越强大。 **最牛**的还是由淘宝的工程师清无...