[英]Window exe API cors issue when calling from any webapp. C++
我們已經使用 CPP 語言創建了一個 EXE 文件,並創建了一個 API,例如http://localhost:5800/get-id/
。 當我在瀏覽器中打開時,返回完美的 output。
當我在 HTML > 腳本頁面中使用fetch
時No "Access-Control-Allow-Origin" header is present on the requested resource.
代碼1:
fetch("http://localhost:5800/get-id/", {method: 'GET').then(function(response) {
console.log(response.text());
}).catch(function(error) {
console.log('Request failed', error)
});
經過研究,我添加了mode: no-cors
error lost but getting a empty response。 代碼2:
fetch("http://localhost:5800/get-id/", {method: 'GET', mode: 'no-cors'}).then(function(response) {
console.log(response.text());
}).catch(function(error) {
console.log('Request failed', error)
});
如果我在任何檢查控制台中使用code2
然后得到一個空的主體但是當我在瀏覽器中打開http://localhost:5800/get-id/
並嘗試在控制台中點擊code2
然后獲得完美的參數。
這意味着,本地主機域它工作正常,但是當它通過我的錯誤從任何域中獲取時。
什么是正確的解決方案? 在 C/CPP 語言中,我們如何允許 cors?
奇怪的:
CORS 是一個復雜的話題,我通常在 Express 服務器的 Node.JS 中使用CORS 中間件來處理它(也許代碼將有助於解決這個問題)。
其目標是允許域api-domain
上的 API 列出可以使用它的 web 應用程序,例如您的應用程序位於webapp-domain
域上。
當應用程序調用fetch('http://api-domain/get-id/')
到另一個域時,它被稱為跨域調用。
所有瀏覽器都會像這樣執行CORS 預檢調用來檢查余量:
OPTIONS /get-id/
Access-Control-Request-Method: GET
Access-Control-Request-Headers: origin, x-requested-with
Origin: http://webapp-domain
(請注意這是對 API 的 OPTION 請求,而不是 GET)
並且響應應列出允許webapp-domain
(並指定允許哪些 HTTP 方法)
HTTP/1.1 204 No Content
Connection: keep-alive
Access-Control-Allow-Origin: http://webapp-domain
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400
像這樣成功的預檢調用后,瀏覽器將繼續fetch
,例如,它將向http://api-domain/get-id/
發送 GET 請求
附言
跳過 CORS 的一種方法是在webapp-domain
中設置 HTTP 代理,該代理將在服務器端調用api-domain
並且不受 CORS 的限制。 有關詳細信息,請參閱此答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.