我有一個最簡單的本地 http 服務器,它連接到從 localhost 提供單個檔案。我可以很好地從瀏覽器導航到資源,但我需要能夠使用fetch瀏覽器控制臺中的web api獲取資源,除非控制臺來自完全相同的 origin ,否則這不起作用。
請注意:
該資源是實時的:
C:\> (Invoke-WebRequest http://localhost:49152/C:/temp/events/62.0.0.32712-0515-834-4.build.Main_events.json).StatusCode
200
C:\>
當控制臺來自同一來源時:

否則:

我知道我可以忽略第一個錯誤 - 提到http://127.0.0.1:9001 的錯誤。所以我的問題是第二個錯誤:
Refused to connect to 'http://localhost:49152/C:/temp/events/62.0.0.32712-0515-834-4.build.Main_events.json' because it violates the document's Content Security Policy.
到目前為止,我無法弄清楚如何解決它。這似乎是經典的 CORS 問題,但在運行fetch瀏覽器時不會發出任何預檢 OPTIONS 請求。我知道這一點,因為我正在運行 Fiddler。它顯示GET來自同一來源的請求,但絕對沒有來自另一個來源的請求。
fetch我試圖使作業的原始代碼是這樣的:
const request = fetch(url)
.then(response => response.blob())
.then(blob => {
globals.dispatch(Actions.openTraceFromFile({
file: new File([blob], fileName),
}));
})
.catch(e => alert(`Could not load local trace ${e}`));
它來自https://www.ui.perfetto.dev/我試圖以非互動方式加載我的跟蹤檔案。
(這個問題與How to open a chrome trace file with ui.perfetto.dev non interactively?和How can I open chrome browser with disabled document's content security policy有關?)
我嘗試使用該--disable-web-security標志運行 chrome ,這應該禁用 CORS 驗證(據我對這個標志的理解)。無濟于事。
我能做些什么讓它發揮作用嗎?
Web服務器源代碼:
function NavigateToFile(
[Parameter(Mandatory)][ValidateScript({ Test-Path $_ -PathType Leaf })]$FilePath,
[scriptblock]$Action
)
{
$port = Get-OpenTcpPort
$http = [Net.HttpListener]::new()
$http.Prefixes.Add("http://localhost:$Port/")
$http.Start()
$FilePath = (Get-Item $FilePath).FullName.Replace('\', '/')
$ExpectedUrl = "$($http.Prefixes)$FilePath"
$ExpectedUrl | ForEach-Object $Action
try
{
$run = $true
while ($http.IsListening -and $run)
{
$context = $http.GetContext()
Write-Host "$($context.Request.HttpMethod) $($context.Request.Url)"
if ($context.Request.HttpMethod -eq 'GET')
{
if ($context.Request.Url -eq $ExpectedUrl)
{
$buffer = [IO.File]::ReadAllBytes($FilePath)
}
else
{
$buffer = [Text.Encoding]::UTF8.GetBytes("Terminated")
$run = $false
}
$context.Response.ContentLength64 = $buffer.Length
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length)
$context.Response.OutputStream.Close()
}
}
}
finally
{
$http.Close();
}
}
uj5u.com熱心網友回復:
這不是 CORS,而是此處定義的內容安全策略:
https://github.com/google/perfetto/blob/master/ui/src/frontend/index.ts#L127
它僅支持從 localhost:9001 獲取以減少攻擊面。
如果你讓你的網路服務器監聽埠 9001 而不是隨機埠,錯誤應該會消失。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405814.html
標籤:
