gpt4 book ai didi

ajax - 从客户端调用服务器端 REST 函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:17 25 4
gpt4 key购买 nike

在这种情况下,在服务器端有一些带有 REST 功能的存档 restApi.js 。我的 REST 函数工作正常,我使用 Prompt Command 进行测试。

在我的客户端有一些存档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)。我需要知道如何解决这个问题,如果有其他最佳实践,请告诉我。

在我的控制台 (Chrome) 中显示我是否调用 ajax 函数: enter image description here

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

如果我点击(BAD Request)显示:Obs.:与 app.js 相同的错误,但 app.js 工作正常。

Cannot GET /restApi.js

在这种情况下,文件restApi.js是索引后面的文件夹。

文件夹:

观察:公共(public)文件夹中有index.ejs

enter image description here

最佳答案

您的问题是网址错误。如果您有这样的 fiule 结构,您必须如图所示指向 Point your Url like this ../restapi.js

关于ajax - 从客户端调用服务器端 REST 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42142167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com