【问题标题】:cURL command works, but Fetch API call returns 200 with 400 validation error in Response PayloadcURL 命令有效,但 Fetch API 调用在响应负载中返回 200 和 400 验证错误
【发布时间】:2019-10-23 19:03:57
【问题描述】:

我在使用 Fetch 发送 POST 请求以缩短 URL 时遇到了一个大问题。

我很好并且能够通过 cURL 命令向这个 url 缩短 API 发出 POST 请求:

卷曲命令

curl -d 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch' http://fakeurlforexample/api/shorten/

回应

{"url": "https://fakeurlforexample/BdzfM3", "long_url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch", "name": "BdzfM3"}

我从 API 获得了这个很棒的响应负载。

但是当我通过Fetch 使用下面提供的代码执行此操作时,我得到 200 OK 并且在响应负载中我有 400 验证错误,我缺少 API 密钥。

但是,开发者控制台中的请求负载显示参数已正确传递给 API(我认为...)

{"api_key":"xxxxxxxxxxxxxxxxx","url":"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"}

这是我的代码:

let get_url = 'http://fakeurlforexample.com/api/shorten/';

    let request = new Request(get_url, {
        method: 'POST', 
        body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
    });

    fetch(request)
    .then(function() {
        console.log(request);
        console.log(request.url);
     })

有人看到我在这里犯的错误吗?

这周现在已经被这个打了好几个小时了。感谢您的任何帮助和帮助!不,我不能像现在这样轻松地将代码转换为 axios。这是一个演示,所以我真的只是想让它发挥作用。

【问题讨论】:

  • 你太棒了,谢谢@DanielBank !!!让我去试试!!!
  • @DanielBank 你在这个周末让我摆脱了更多的压力,让我在周一开始工作!!!我将其设置为 content-type application/x-www-form-urlencoded 并将参数更改为长字符串和中提琴!谢谢!!
  • 继续做吧:) 完全,我会做的! @DanielBank 再次感谢!

标签: javascript curl fetch fetch-api


【解决方案1】:

可能是因为您定义了 2 次标头。

【讨论】:

  • 更新了代码,但仍然出现同样的错误,没有任何新的错误。感谢@İbrahim 的回复!
【解决方案2】:

来自-d, --data <data> 上的curl manpage 选项部分:

(HTTP) 将 POST 请求中的指定数据发送到 HTTP 服务器,就像浏览器在用户填写 HTML 表单并按下提交按钮时所做的一样。这将导致 curl 使用 content-type application/x-www-form-urlencoded 将数据传递给服务器。与 -F、--form 比较。

而您的请求是发送一个 JSON 对象(内容类型:application/json):

let request = new Request(get_url, {
  method: 'POST', 
  body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});

既然您知道 API 端点接受 application/x-www-form-urlencoded 是因为 curl 请求成功,您可以将内容类型设置为 application/x-www-form-urlencoded 并将正文作为字符串发送:

let request = new Request(get_url, {
  method: 'POST',
  headers: new Headers({'content-type': 'application/x-www-form-urlencoded'}),
  body: 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-07
    • 2019-08-22
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2021-11-09
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多