この場合、サーバ側では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>
私は他の人の例を参照してみてくださいましたが、動作しません(アヤックス)。 そして、私はこれを解決する方法を知る必要があります。もし他のベストプラクティスがあれば、私に知らせてください。私のコンソール(クローム)私はAjaxの機能を呼び出す場合を示して
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
をそして、私は(不正な要求)のショーをクリックした場合: OBS:app.jsよりも、同じエラー、 app.jsは正常に動作します。
Cannot GET /restApi.js
この場合、ファイルrestApi.jsはインデックスの背後にあるフォルダです。
フォルダ:
OBS:パブリックフォルダは、私はあなたがAJAX経由で掲示されているデータが正しい構文ではないと思うの誤差に基づいてindex.ejs
「うまくいきません。どのように動作しないのですか?エラーや例外がありますか?予期しない動作が気づいていますか? –
本当に申し訳ありませんが、編集します –
期待したデータをAPIに送信していますか? 1つのプロパティ "sendData"を持つオブジェクトが必要ですか?私はそれに基づいて答えを掲示しました。 –