javascript - cURL 命令有效,但 Fetch API 调用返回 200,响应负载中出现 400 验证错误

标签 javascript curl fetch fetch-api

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

我很好,能够通过 cURL 命令向此 url 缩短器 API 发出 POST 请求:

curl 命令

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” ,“名称”:“BdzfM3”}

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

但是当我通过 Fetch 这样做时使用下面提供的代码,我得到 200 OK,并且在响应负载中出现 400 验证错误,表明我缺少 API key 。

但是,开发人员控制台中的请求有效负载显示参数已正确传递到 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。这是一个演示,所以我只是想让它发挥作用。

最佳答案

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

(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -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'
});

关于javascript - cURL 命令有效,但 Fetch API 调用返回 200,响应负载中出现 400 验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56508437/

相关文章:

javascript - 单击 react 中的元素时如何更改存储在 LocalStorage 中的数据?

javascript - 如何计算对象属性已更改的次数

web-services - 在一个 POST 命令中卷取多个数据

javascript - 如何延迟页面渲染直到从 api 收到数据

mysql - 获取所有行,直到匹配一个特殊行

php - 如何重用一个 html head 部分?

json - 在 shell 中处理 json 时,如何正确地将多个 jq 语句链接在一起,例如使用 curl?

json - 使用 json 数据将 curl post 形成为 swift http post

javascript - 使用 typescript 在 Node 项目中导入 Node 获取

javascript - 如何使用 JavaScript 删除特定网站的 cookie?