gpt4 book ai didi

Javascript - 在 localhost 上使用 fetch 和 URL 参数

转载 作者:行者123 更新时间:2023-12-05 00:28:06 29 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












此问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是 on-topic在这里,这个问题的解决方式不太可能帮助 future 的读者。


3年前关闭。







Improve this question




我有一个 NodeJS 服务器在我的计算机的 3001 端口上运行。我可以使用 fetch访问 localhost 端点,如下所示:fetch("/api_endpoint") .

但是,我还想在我的 GET 请求中包含 url 参数。

通常,我可以通过这样做来包含 url 参数:

const url = new URL("localhost:3001")
const params = { sources: JSON.stringify(this.state.sources), timeRange: JSON.stringify(this.state.timeRange), minReacts: this.state.minReacts }
url.search = new URLSearchParams(params)
let data = await fetch(url)

但是,这会引发错误:

Fetch API cannot load localhost:3001?sources=%5B%22Confessions%22%2C%22Summer+Confessions%22%2C%22Timely+Confessions%22%5D&timeRange=%5B%222017-01-12T23%3A35%3A07.666Z%22%2C%222019-01-12T23%3A35%3A07.667Z%22%5D&minReacts=20. URL scheme must be "http" or "https" for CORS request.



如何使用创建与 localhost 一起使用的获取请求,该请求也使用 URL 参数?

编辑:

添加 http://到前面并不能解决问题。

Access to fetch at 'http://localhost:3001/?sources=%5B%22Confessions%22%2C%22Summer+Confessions%22%2C%22Timely+Confessions%22%5D&timeRange=%5B%222017-01-13T00%3A00%3A17.309Z%22%2C%222019-01-13T00%3A00%3A17.310Z%22%5D&minReacts=20' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

最佳答案

根据 Quentin 的建议,我需要添加 http://localhost:3001 前面.代码变成了:

const url = new URL("http://localhost:3001")

之后,我需要在我的服务器上启用 cors 以修复另一个错误。

因为我用的是express,所以我只跑了 npm install cors然后将以下两行添加到我的服务器:
const cors = require("cors")
app.use(cors())

关于Javascript - 在 localhost 上使用 fetch 和 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54164874/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com