直接发布一个class类
发布于 8 年前 作者 gzhangzy 4608 次浏览 来自 分享

引言

一个web服务器发布html文件,通过CGI接口,程序也可以对请求/回应数据流进行加工。那web服务器可以发布一个class类吗?

发布一个class类是什么意思?

当你用nodejs在后端写了一个class类,希望被前端或远程其他nodejs调用。这时你该怎么办?…还得一阵猛忙活,然后宣称提供了一个什么RESTful之类的接口。

把class直接发布行不行?就是在浏览器中或远程其他nodejs中直接调用,就像在你的后端直接调用一个模块一样。这就叫发布一个class 类。

先看一个演示程序

演示的例子当然叫HelloWorld了:-),这是惯例。

编写一个类HelloWorld.es6

class HelloWorld {
    constructor() {
        this.greeting = 'Hello World!';
    }
    welcome(callback) {
        callback(this.greeting);
    }
}

export default HelloWorld;

使用babel转成ES5

$ babel HelloWorld.es6 -o HelloWorld.js

如果你还不会使用babel,那就使用babel官网转吧!转完的文件叫HelloWorld.js

现在要把你写好的class发布出去了!

# npm install nodeway -g

安装nodeway,这一步应该没什么可解释的。能解释的就是这个名字,还不想解释。

使用nodeway命令,把你写的HelloWorld这个类发布出去吧!

# nodeway --class HelloWorld.js --host 0.0.0.0 --port 8080 --docs . &

这句的意思是启动一个Web Server,把HelloWorld.js发布出去。 好了,现在剩下的就是测试了。

编写测试程序 index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>HelloWorld</title>
    <script type="text/javascript" src="/HelloWorld.js"></script>
</head>
<body>
<script>
var api = new HelloWorld.default;
api.welcome(function(greeting) {
    document.write(greeting);
});
</script>
</body>
</html>

用浏览器访问你写的这个index.html文件,就可以看到你发布成功了。 简单吧?还能再简单点不?能呀!如果你懒得安装nodeway包,那就把下面内容贴到你的Web服务器下

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>HelloWorld</title>
    <script type="text/javascript" src="http://yishizhencang.com:8080/HelloWorld.js"></script>
</head>
<body>
<script>
var api = new HelloWorld.default;
api.welcome(function(greeting) {
    document.write(greeting);
});
</script>
</body>
</html>

这有什么不同?原来<script>标签中src变了!远程执行我发布的HelloWorld类?这是跨域访问呀?这也能行? 当然没问题了,你试试就知道了。

还有什么新鲜的吗?有啊!你可以用node远程调用HelloWorld类。vi welcome.js,写如下代码:

var requireFromUrl = require('require-from-url');

requireFromUrl("http://yishizhencang.com:8080/HelloWorld.js")
   .on('Resolved', function(next, HelloWorld) {
        var api = new HelloWorld.default;
        api.welcome(function(greeting) {
            console.log(greeting);
        });
    })
   .on('Rejected', function(next, e) {
        console.log(e);
    });

requireFromUrl是什么?就是require!只不过是从URL中加载。

$ npm install require-from-url
$ node welcome.js

以上这个例子,可以通过如下命令下载

$ npm install nodeway-helloworld

好了,就写这么多了。

2 回复

增加支持JSON-RPC了,让其他语言也能访问。

回到顶部