我正在遷移到 Angular 13,我想使用 HttpClient 而不是 jQuery.ajax。
以下 jquery 代碼有效:
function asyncAjax(url: any){
return new Promise(function(resolve, reject) {
$.ajax({
type: 'POST',
crossDomain: true,
xhrFields: {
withCredentials: true
},
url: url,
data: null,
contentType: "text/plain; charset=utf-8",
dataType: "json",
success: function(data) {
resolve(data) // Resolve promise and when success
},
error: function(err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
...
const json: any = await asyncAjax(url);
但是,當我使用 HttpClient 時:
private readonly _httpClient: HttpClient;
constructor(httpClient: HttpClient) {
this._httpClient = httpClient;
}
...
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
const json = await firstValueFrom(this._httpClient.post<T[]>(url, null,
{ headers: headers, withCredentials: true}));
我得到:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. (Reason: CORS request external redirect not allowed).
誰能說如何使它與 HttpClient 一起作業?
uj5u.com熱心網友回復:
在您的 jQuery 代碼中,您根本沒有發送任何資料并聲稱您正在發送純文本。
data: null, contentType: "text/plain; charset=utf-8",
在您的 Angular 代碼中,您仍然沒有發送任何資料,但這次您聲稱您正在發送JSON。
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
JSON 不是HTML 表單支持的資料型別,這意味著在跨域請求上發送它,瀏覽器將發送一個預檢請求。
服務器在回應該預檢請求時未使用 CORS 授予權限,并且似乎正在發出重定向。
這里快速而骯臟的解決方案是發送與代碼作業時相同的標頭。 Content-Type
更好的解決方案是考慮您的 API 設計。為什么您首先使用 POST 請求而不是 POST 任何資料?可能這應該是一個 GET 或 DELETE 請求。
重定向的原因也可能是 的值url已更改(可能從http://example.com/foo/到http://example.com/foo)并且需要更正。
uj5u.com熱心網友回復:
我猜該jQuery版本正在利用該crossDomain: true功能繞過 CORS 限制 - 這是特定于jQuery并在引擎蓋下使用 JSONP
如果我是對的,Angular JSONP 檔案可能會有所幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463327.html
標籤:javascript jQuery 有角度的 阿贾克斯 跨域
上一篇:檢測觸摸設備上的“長按”
