上一篇介紹使用 SAP Web IDE 代理來解決 Cross-origin 問題。如果使用 Eclipse 作為開發(fā)工具,可以使用 Simple proxy servlet 來測試,作為 cross-origin 的代理。但 SAP Web IDE 編寫的代碼,并不能在不做任何修改的情況下運(yùn)行。為了能較好地實(shí)現(xiàn)代碼移植,另外一個(gè)比較好的方法是使用 Grunt。Grunt 是基于 JavaScript 的自動(dòng)化工具,可以用于 OpenUI5 的測試運(yùn)行,實(shí)現(xiàn)跨域代理。
環(huán)境準(zhǔn)備
- 安裝
Node.js - 使用 npm 工具 ( Node.js 的包管理器 ) 安裝
grunt-cli,安裝的命令如下:
npm install -g grunt-cli
在 Windows 下,應(yīng)該以管理員權(quán)限來運(yùn)行該命令。上述命令執(zhí)行完后,grunt 命令就被加入到你的系統(tǒng)路徑中了,以后就可以在任何目錄下執(zhí)行此命令了。
安裝 grunt-cli 并不等于安裝了 Grunt!Grunt CLI 的任務(wù)很簡單:調(diào)用與 Gruntfile 在同一目錄中 Grunt。這樣帶來的好處是,允許你在同一個(gè)系統(tǒng)上同時(shí)安裝多個(gè)版本的 Grunt。
Grunt 工具搭建
Grunt 需要將如下兩個(gè)文件放置在項(xiàng)目的根目錄下面。
-
package.json: 這個(gè)文件告知
grunt-cli需要安裝的依賴。 - Gruntfile: 此文件被命名為 Gruntfile.js 或 Gruntfile.coffee,用來配置或定義任務(wù)(task)并加載 Grunt 插件
package.json 文件的內(nèi)容如下:
{
"name": "scn-demo-gw-sample",
"version": "0.0.1",
"devDependencies": {
"grunt": "^1.0.1",
"grunt-connect-proxy": "^0.2.0",
"grunt-contrib-connect": "^1.0.2",
"grunt-contrib-watch": "^1.0.0",
"jit-grunt": "^0.10.0"
}
}
Gruntfile.js 文件內(nèi)容如下:
module.exports = function (grunt) {
'use strict';
// load grunt plugins
require('jit-grunt')(grunt, {
configureProxies: 'grunt-connect-proxy'
});
// create config
grunt.initConfig({
settings: {
connect: {
host: 'localhost',
port: '9555'
},
proxy: {
host: 'dph01.nodomain',
port: '8180'
}
},
connect: {
options: {
hostname: '<%= settings.connect.host %>',
port: '<%= settings.connect.port %>',
livereload: 35729,
middleware: function (connect, options, defaultMiddleware) {
var aMiddlewares = [];
aMiddlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest);
aMiddlewares.push(defaultMiddleware);
return aMiddlewares;
}
},
connectWebapp: {
options: {
base: ['webapp'],
open: true
}
},
proxies: [
{
context: '/resources',
host: '<%= settings.proxy.host %>',
port: '<%= settings.proxy.port %>',
https: false,
rewrite: {
'/resources': '/sap/public/bc/ui5_ui5/resources'
}
}, {
context: '/sap/opu/odata',
host: '<%= settings.proxy.host %>',
port: '<%= settings.proxy.port %>',
https: false
}
]
},
watch: {
options: {
livereload: true
},
watchWebapp: {
files: ['webapp/**/*']
}
}
});
// register serve task
grunt.registerTask('serve', ['configureProxies:server', 'connect:connectWebapp', 'watch:watchWebapp']);
// register default task
grunt.registerTask('default', ['serve']);
}
grunt.initConfig 需要根據(jù) SAP 服務(wù)器的對外提供 OData service 的 domain 進(jìn)行修改:
grunt.initConfig({
settings: {
connect: {
host: 'localhost',
port: '9555'
},
proxy: {
host: 'dph01.nodomain',
port: '8180'
}
},
然后在項(xiàng)目根目錄下運(yùn)行如下命令:
npm install
npm 根據(jù) package.json 文件的依賴,在本地安裝相關(guān)的插件。
測試 Grunt 服務(wù)
在項(xiàng)目根目錄下,運(yùn)行 grunt serve 命令,grunt 在本地創(chuàng)建 Web 服務(wù),并代理連接到后端 SAP 系統(tǒng)。