Fetch-API请求失败(获取和发布)。我很迷失
我为20年以上的钱编写了代码,但是我没有任何借口来解决这个问题。
哦,我谷歌搜索了。我知道这里有许多半相同的问题,我认为我已经阅读了所有答复,并尝试了所有建议的模式。许多问题的表达不是特别好,我的情况似乎有些自相矛盾(所有部分都孤立起作用)。请忍受我,我会尽力而为。
在前面使用苗条的套件,后面使用FastApi。
首先,下面是我的“ button.svelte”组件,完整复制了逐字化。
<script lang="javascript">
async function worksJustFine() {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(response => {
console.log(" response", response)
console.log(" r.json() >", response.clone().json())
response.json()
.then(json => {
console.log("json", json)
})
.catch(error => console.log(error))
})
}
async function doesNotWork() {
fetch(`http://localhost:8000/api/test_url?test_param=1`)
.then(response => {
console.log(" response", response)
console.log(" r.json() >", response.clone().json())
response.json()
.then(json => {
console.log("json", json)
})
.catch(error => console.log(error))
})
}
</script>
<buttons>
<button class="btn btn-outline-primary btn-lg" on:click={worksJustFine}>OK</button>
<button class="btn btn-outline-primary btn-lg" on:click={doesNotWork}>NOT OK</button>
</buttons>
<style lang="scss">
</style>
其次,下面是路由/视图:
@router.get("/api/test_url")
async def test_url(test_param: str):
try:
print(f"test_param: {test_param}")
return {"success": True, "message": "Message", "hooray": True}
except Exception as e:
print(repr(e))
return {"success": False, "message": repr(e), "": True}
问题表现出来:
“不确定”按钮启动了一个永不返回的请求,而网络面板仅显示标准的pebkac”(待处理)“(待处理)”请求,似乎永远是永远的。对于Chromium和Chrome来说,这是正确的,尽管上面的请求确实从Firefox(最新和DEV)工作。
。Fastapi URL使用Chrome稳定,Chromium和Firefox的新标签中的curl,失眠和浏览器的直接请求完美地工作。
如果我使用POST请求(这是我的目标),那么它根本无法从任何浏览器中使用。永远,永远。但是,从卷发,邮递员等发射时,该帖子确实可以正常工作
有时我单击它然后走开。很少有未指定的时间(半小时,小时?)我返回 - 发现它确实确实是工作 - 请求通过,副作用很明显。我认为这总共发生了,在三天的挣扎中进行了两次。
这不是CORS。如果我禁用下面的代码,它将成为CORS问题,但是对于此代码,似乎很清楚。另外,如上所述,FF的工作正常,他大概也尊重CORS。
app = FastAPI()
app.add_middleware(CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"])
app.include_router(router)
我的一个浏览器都没有安装任何插件或adblockers。在我的主要浏览器(QTWebengine/QuteBrowser)中,我有一个greasemonkey脚本来快速向前youtube广告,还有几个用户-CSS文件。
我阅读的帖子和文章中的一个共同线程是,情况可能会有所不同,具体取决于调试工具面板是否打开。就我而言,这与情况完全没有任何影响。
所有事物都在Localhost上运行 - 没有VM,没有容器...只有我和Localhost。
由于
worksjustfine
工作正常,因此似乎不是一个聪明/javascript问题。由于
test_url
从fetch api以外的每个源工作正常(作为帖子或get),这似乎不是fastapi问题。
我想念什么?我可以提供什么进一步的信息?
I've written code for money for 20+ years, I have no excuse for this question though.
And oh boy have I googled it. I know that there are many semi-identical questions here, and I think I have read all of the responses, and tried all of the patterns suggested. Many of the questions are not particularly well articulated, and my case seems a little paradoxical (all parts work in isolation). Please bear with me and I will do my best.
Using svelte-kit on the front, and fastapi on the back.
First, below is my "Buttons.svelte" component, copied verbatim in its entirety.
<script lang="javascript">
async function worksJustFine() {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(response => {
console.log(" response", response)
console.log(" r.json() >", response.clone().json())
response.json()
.then(json => {
console.log("json", json)
})
.catch(error => console.log(error))
})
}
async function doesNotWork() {
fetch(`http://localhost:8000/api/test_url?test_param=1`)
.then(response => {
console.log(" response", response)
console.log(" r.json() >", response.clone().json())
response.json()
.then(json => {
console.log("json", json)
})
.catch(error => console.log(error))
})
}
</script>
<buttons>
<button class="btn btn-outline-primary btn-lg" on:click={worksJustFine}>OK</button>
<button class="btn btn-outline-primary btn-lg" on:click={doesNotWork}>NOT OK</button>
</buttons>
<style lang="scss">
</style>
Second, below is the route/view:
@router.get("/api/test_url")
async def test_url(test_param: str):
try:
print(f"test_param: {test_param}")
return {"success": True, "message": "Message", "hooray": True}
except Exception as e:
print(repr(e))
return {"success": False, "message": repr(e), "": True}
The problem manifests like this:
The "NOT OK" button initiates a request which never returns, and the network panel shows only the standard pebkac "(pending)" request, seemingly forever. This is true for Chromium and Chrome, though both GET requests above DO work from Firefox (latest and dev).
The fastAPI URL works perfectly from curl, from insomnia, and from a direct request from the browser in a new tab, using chrome-stable, chromium and Firefox.
If I use a POST request (which is my goal), then it does not work from any browser, at all, ever. Pending, forever. The POST does however work fine when fired from curl, postman etc.
Sometimes I click it and walk away. Rarely, after an unspecified time (half hour, hour?) I return - and find that it DID in fact, work - the request went through, the side effects are obvious. I think this has happened in total, twice over three days of struggle.
It isn't CORS. If I disable the code below, it becomes a CORS issue, but with this code it seems clear. Also, as above, it works fine from FF, who presumably respects CORS too.
app = FastAPI()
app.add_middleware(CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"])
app.include_router(router)
None of my browsers have any addons or adblockers installed. In my main browser (qtwebengine/qutebrowser) I have a single greasemonkey script to fast-forward youtube ads, and a couple of user-css files.
One common thread among the posts and articles I have read, is that the situation can be different depending on whether or not the debug tools panel is open. In my case, this does not make any difference at all to the situation.
Everything is running on localhost - there are no VMs, no containers... just me and localhost.
Due to the fact that
worksJustFine
works just fine, it does not appear to be a svelte/javascript issue.Due to the fact that
test_url
works fine (as POST or GET) from every source other than the fetch API, it does not appear to be a fastAPI issue.
What am I missing? What further information can I provide?
insomnia request, fastapi has not been restarted, chromium request is still pending
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您抽出宝贵的时间在这里阅读和评论。我已经克服了这个问题,尽管我没有净化残留的混乱。
我是没有软件的,SSE连接有限制 - 这是铬的6个硬封(Firefox还声称是这种情况,并且两者都被标记为Wontfix)。
我正好使用6个SSE连接到不同的流数据点。
我禁用了所有SSE端点,并且获得/发布完美地工作。然后,我会逐步重新启用所有 SSE端点....
现在,当我在上面问我的问题时,系统与状态完全没有变化!但是,GET请求从Chrome和Chromium中起作用,并且POST请求都可以从所有浏览器中起作用。
我理解错误的根源,并且我将SSE指定为“被视线的Websocket代替”。
再次感谢您抽出宝贵的时间与我交谈。
“我希望我能拥抱你们所有人……但是我不会”
Thank you for taking time to read and comment here. I have overcome the issue, although I am not purified of residual confusion.
I was unware that there was a limit on SSE connections - this is hard-capped at 6 in Chromium (firefox also claims that this is the case, and both are flagged wontfix).
I was using exactly 6 SSE connections for different streaming datapoints.
I disabled all SSE endpoints, and GET/POST worked perfectly. I then incrementally re-enabled ALL the SSE endpoints....
Now, the system is precisely unchanged from its state when I asked my question above! However, the GET request works from Chrome and Chromium, and the POST request works from all browsers.
I understand the source of the error, and I've earmarked SSE as "crap to be replaced by websockets on sight".
Thanks again for taking time to talk to me.
"I wish I could just hug you all... but I'm not gonna"