我在bluemix上创建了一个与业务规则服务绑定的nodeapp,并且我在mobilefirst上托管了另一个应用程序,我创建了我的应用程序UI。我想从mobilefirst应用程序发送数据并接收数据,我被告知要使用cors请求,但我不知道如何做到这一点。
这是我的 app.js 文件:
var app = require("express")(),
restler = require("restler"),
bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type, Accept");
next();
});
app.post("/", function(request, response) {
var options = {
username: "resAdmin",
password: "replace"
};
var url = "https://brsv2-6855bc66.ng.bluemix.net/DecisionService/rest" + "/vacationsRuleApp/1.0/vacationsRuleProject/json";
restler.postJson(url, request.body, options).on('complete', function(data) {
response.send(data);
});
});
app.listen(process.env.VCAP_APP_PORT || 8080);
这是我的客户端代码:
$.post(
"http://businessrules-vacationsruleapp.mybluemix.net/",
{
"employeeID": "jujuju",
"loanAmount": 10517320,
"theEmployee": {
"seniority": 3,
"annualSalary": 10517320,
"nbOfExtraVacationDaysBasedOnSeniority": 10517320
},
"creditAmount": 20000,
"__DecisionID__": "string",
"AnnualSalary": 20000 },
function( data ) {
alert(JSON.stringify(data));
console.log(data);
}
);
答案 0 :(得分:2)
您需要在app.js
中加入以下内容。以下内容将允许CORS发出请求。
<强> app.js 强>
var app = require("express")(),
restler = require("restler"),
bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post("/", function(request, response) {
var options = {
username: "replace",
password: "replace"
};
var url = "https://brsv2-6855bc66.ng.bluemix.net/DecisionService/rest" + "/vacationsRuleApp/1.0/vacationsRuleProject/json";
restler.postJson(url, request.body, options).on('complete', function(data) {
response.send(data);
});
});
app.listen(process.env.VCAP_APP_PORT || 8080);
然后客户端使用JQuery,您可以执行以下操作。
$.ajax ({
url: "https://businessrules-vacationsruleapp.mybluemix.net",
type: "POST",
data: JSON.stringify({
"employeeID": "jujuju",
"loanAmount": 10517320,
"theEmployee": {
"seniority": 3,
"annualSalary": 10517320,
"nbOfExtraVacationDaysBasedOnSeniority": 10517320
},
"creditAmount": 20000,
"__DecisionID__": "string",
"AnnualSalary": 20000 }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data){
console.log(data);
$(".result").text(JSON.stringify(data));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result"></div>
您从通话后发送的任何对象都将被发送到业务规则服务。
答案 1 :(得分:1)
CORS npm模块使用它非常容易使用Express。
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());