Javascript - 在带有 URL 参数的本地主机上使用 fetch

Javascript - Use fetch on localhost with URL parameters

我在计算机的 3001 端口上有一个 NodeJS 服务器 运行。我可以使用 fetch 访问本地主机端点,如下所示: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.

我如何使用创建一个与本地主机一起工作的提取请求也使用 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.

按照昆汀的建议,我需要在localhost:3001前面加上http://。代码变为:

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

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

因为我使用的是 express,所以我只是 运行 npm install cors 然后将以下两行添加到我的服务器:

const cors = require("cors")
app.use(cors())