我在使用 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/