【问题标题】:Fetch API blocked, but not AJAX or XHR获取 API 被阻止,但不是 AJAX 或 XHR
【发布时间】: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?我发现fetch API 不会 通过 default => MDN docs 发送/接收 cookie

标签: javascript jquery ajax xmlhttprequest fetch


【解决方案1】:

你只需要像这样对正文进行字符串化

body: JSON.stringify({ url: "https://google.com/" }),

所以整个代码会是这样的

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: JSON.stringify({ url: "https://google.com/" }),

})
.then(response => {
    console.log(response);
})
.catch(err => {
    console.log(err);
});

【讨论】:

  • 感谢@Pratham 的回答!看来你说对了一半。我所做的就是按照你所说的去做——JSON.stringify()body 对象。然后我将content-type 更改为application/json。最后,我添加了另一个.then() 块。第一个使用 fetch API 的 response.json() 转换响应,第二个 console.logs 数据。在此处查看示例:jsfiddle.net/Ludolfyn/shmfrxo6。如果您想通过这些更改更新您的答案,那么我非常乐意将您的答案标记为解决方案:)
猜你喜欢
  • 2020-10-27
  • 2019-09-04
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 2011-11-01
  • 1970-01-01
  • 2020-08-07
相关资源
最近更新 更多