【发布时间】:2018-01-13 12:57:59
【问题描述】:
我正在用 express 编写一个网络应用程序,其中一个资源通过一个 API 公开,其端点位于“api/tone”上。 API 只是 Watson 服务之一的包装器,但我不直接调用它们,以免在前端进行所有身份验证和有效负载构建。 API 本身运行良好,因为当我尝试使用 POSTMAN 访问它时,它会正确响应。
POSTMAN 请求信息:
POST:本地主机:3000/api/tone
标题:“content-type”:“application/x-www-form-urlencoded”
Body:“text”:“国王是个可爱的小伙子。他让我觉得我和家人回到了家。”
此请求完全按预期工作。
该应用只是展示其他功能的原型,因此它不使用任何类型的身份验证。
Javascript 请求
当我尝试从前端调用 API 时出现问题。
function sendRequest(text) {
var payloadToWatson = {};
payloadToWatson.text = text;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText);
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", messageEndpoint, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(JSON.stringify(payloadToWatson));
}
在这里我收到一个 POST 错误请求错误。当我在后端记录错误时,这会消失:
{"code":400,"sub_code":"C00007","error":"No text given","x-global-transaction-id":"ffea405d5a5a00dd017a0dbb"}
我 99% 确定问题出在前端 API 调用程序中,否则 POSTMAN 请求将无法工作,但我仍然无法找到如何使其工作。
【问题讨论】:
标签: javascript node.js watson