在这种情况下,服务器端有一些归档文件restApi.js
和REST
函数。我的REST函数工作正常,我用提示命令测试。从客户端调用服务器端REST功能
在我的客户端有一些存档index.ejs
,我想打电话给这个文件。
我restApi.js:服务器端
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID:)([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
我index.ejs:客户端
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
我已经尝试看看别人的例子,但不工作(阿贾克斯)。 我需要知道如何解决这个问题,如果有其他最佳做法,请让我知道。
SyntaxError: Unexpected token s in JSON at position 2
at JSON.parse (<anonymous>)
at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17)
at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
如果我点击(错误请求)显示: 实验值:同样的错误比app.js,但是app.js工作正常。
Cannot GET /restApi.js
在这种情况下该文件restApi.js是该指数后面的文件夹。
文件夹:
实验值:公用文件夹有index.ejs
点,如图所示“但不工作”有什么不行?它如何不起作用?你看到任何错误或异常?你注意到了什么意外的行为? –
我真的很抱歉,我编辑 –
您是否将预期的数据发送给api?它是否期望只有一个属性为“sendData”的对象?我已经发布了基于此的答案。 –