【发布时间】:2021-11-10 17:03:30
【问题描述】:
我使用源提供的确切代码对 URL 缩短器进行了 API 调用。 Fetch 返回 400 错误(错误请求),但 JQuery 和 XHR 都返回缩短的 URL,没有任何问题。这是为什么?
我尝试将mode: 'no-cors' 和"crossDomain": true 添加到请求中,但都不起作用。
→ Image of What each request returns here
这是我的代码:
(获取)
fetch("https://url-shortener-service.p.rapidapi.com/shorten", {
"method": "POST",
"headers": {
"x-rapidapi-host": "url-shortener-service.p.rapidapi.com",
"x-rapidapi-key": "SIGN-UP-FOR-KEY",
"content-type": "application/x-www-form-urlencoded"
},
"body": {
"url": "https://google.com/"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
(XHR)
var data = "url=https%3A%2F%2Fgoogle.com%2F";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://url-shortener-service.p.rapidapi.com/shorten");
xhr.setRequestHeader("x-rapidapi-host", "url-shortener-service.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "SIGN-UP-FOR-KEY");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data);
(JQuery)
var settings = {
"async": true,
"crossDomain": true,
"url": "https://url-shortener-service.p.rapidapi.com/shorten",
"method": "POST",
"headers": {
"x-rapidapi-host": "url-shortener-service.p.rapidapi.com",
"x-rapidapi-key": "SIGN-UP-FOR-KEY",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"url": "https://google.com/"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
【问题讨论】:
-
你试过
credentials: 'include'吗? -
查看chrome控制台中的请求头和参数,找出调用之间的差异
-
感谢您的回复!我会尝试这些并回复你:)
-
@Noob
credentials: 'include'似乎不起作用。 -
服务器/服务是否依赖 cookie?我发现
fetchAPI 不会 通过 default => MDN docs 发送/接收 cookie
标签: javascript jquery ajax xmlhttprequest fetch