我尝试POST
到我服务器上的API端点。我知道我的端点有效,因为如果我使用高级REST客户端,我可以点击它并按预期获得JSON响应。问题似乎是,尽管调用包含键值对的request.write(postData)
,但我的请求正文中仍未发送任何数据。如果没有在正文中发送此数据,我的服务器会在没有此信息的情况下按预期返回401错误。打印出POST服务器端的内容是空的,但我不知道为什么它是空的。
var postData = querystring.stringify({
"access_token" : accessToken,
"id": applianceId
});
var serverError = function (e) {
log("Error", e.message);
context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server"));
};
var callback = function(response) {
var str = "";
response.on("data", function(chunk) {
str += chunk.toString("utf-8");
});
response.on("end", function() {
result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId);
context.succeed(result);
});
response.on("error", serverError);
};
var options = {
hostname: REMOTE_CLOUD_HOSTNAME,
port: 443,
path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var request = https.request(options, callback);
request.on("error", serverError);
//This doesn't seem to write anything since if I print out the POST
//data server-side it's empty; however, if I print out the value of
//postData here, it looks as expected: 'access_token=xxxxx'
request.write(postData);
request.end();
答案 0 :(得分:0)
我再次测试你的代码httpbin.org/post
,似乎它正在运行。
我认为这个问题与你应该发布application/json
而不是" application/x-www-form-urlencoded
请尝试更改标题
headers: {
"Content-Type": "application/json"
}
然后,尝试将postData更改为JSON字符串:
var postData=JSON.stringify({access_token:"xxxxx"})
要确保您成功发送问题并且问题不是本地问题(可能是服务器中存在问题),请将目标更改为镜像网址:
var options = {
hostname: "httpbin.org",
path:'/post',
port: 443,
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
如果你的NodeJS版本没有问题,那就是你应该得到的回应:(这意味着服务器得到了发布的数据)
{
"args": {},
"data": "{\"access_token\":\"xxxxx\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": {
"access_token": "xxxxx"
},
"origin": "5.29.63.30",
"url": "https://httpbin.org/post"
}
顺便说一句:我真的建议你搬到图书馆来管理你的请求: