我正在使用express编写一个Web应用程序,其中一个资源是通过一个带有'api / tone'端点的API公开的。 API只是Watson服务之一的包装器,但我没有直接调用它们,以免在前端进行所有身份验证和有效负载构建。 API本身工作正常,因为当我尝试使用POSTMAN访问它时,它会正确响应。
POST :localhost:3000 / api / tone
标题:“content-type”:“application / x-www-form-urlencoded”
身体:“文字”:“国王是一个可爱的家伙。他让我觉得我和家人一起回家了。”
此请求完全符合预期。
该应用只是展示其他功能的原型,因此它不使用任何形式的身份验证。
当我尝试从前端调用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”:“没有给出文字”,“x-global-transaction-id”:“ffea405d5a5a00dd017a0dbb”}
我99%肯定问题是在前端API调用者中,否则,POSTMAN请求将无法正常工作,但我仍然无法找到如何使其工作。
答案 0 :(得分:0)
问题是你没有发送同样的东西。邮递员,你不发送json。
只需发送text
而无需字符串化:
xhttp.send({text: text});
答案 1 :(得分:0)
var payloadToWatson = {};
payloadToWatson.text = text;
...
xhttp.send(JSON.stringify(payloadToWatson));
我必须做的是在参数和值之间使用等号创建一个字符串:
var data = "text=" + text;
xhttp.send(data);
现在完美运作。