You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express搭建的Watson包装API,Postman可正常调用但JavaScript请求报错

问题根源与解决方案

嘿,我一眼就瞅出问题所在啦!你在Postman里用的是application/x-www-form-urlencoded格式的表单键值对请求体,但前端代码却把对象转成JSON字符串发送了——这就导致后端解析时找不到text参数,才会返回No text given的错误。

核心问题拆解

你明明设置了正确的请求头Content-type: application/x-www-form-urlencoded,但发送的内容却是JSON.stringify(payloadToWatson)生成的JSON字符串(比如{"text":"The king is a lovely chap..."})。后端期望的是text=The%20king%20is%20a%20lovely%20chap...这种表单格式的键值对,自然会解析失败。

修正后的代码

方案1:直接构造表单字符串(适合单个参数场景)

function sendRequest(text) {
  // 对文本进行URI编码,避免特殊字符破坏格式
  var formPayload = "text=" + encodeURIComponent(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(formPayload); // 发送表单格式字符串,而非JSON
}

方案2:通用对象转表单函数(适合多参数场景)

如果以后需要传递多个参数,可以写一个通用转换函数,避免重复造轮子:

// 把JS对象转换成符合x-www-form-urlencoded规范的字符串
function objToFormData(obj) {
  return Object.keys(obj).map(key => {
    // 对键和值都做URI编码,防止特殊字符引发的解析错误
    return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`;
  }).join('&');
}

function sendRequest(text) {
  var payloadToWatson = { text: text };
  var formPayload = objToFormData(payloadToWatson);
  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(formPayload);
}

为什么这样能解决问题?

当你发送表单格式的字符串时,后端会按照application/x-www-form-urlencoded的规则解析请求体,就能正确提取到text参数——这和你在Postman里的请求行为完全一致,自然就能得到预期的响应啦。

内容的提问来源于stack exchange,提问作者AndresArpi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:04:41