7

I have a NodeJS server running on port 3001 of my computer. I can use fetch to access a localhost endpoint, like this: fetch("/api_endpoint").

However, I also want to include url parameters in my GET request.

Normally, I could include url parameters by doing this:

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)

However, this throws an error:

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.

How can I use create a fetch request that works with localhost that also uses URL parameters?

Edit:

Adding http:// to the front doesn't fix the problem.

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.

Foobar
  • 7,458
  • 16
  • 81
  • 161

1 Answers1

23

As per Quentin's advice, I needed to add http:// in front of localhost:3001. The code became:

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

Afterwards, I needed to enable cors on my server in order to fix another error.

Because I was using express, I just ran npm install cors and then added the following 2 lines to my server:

const cors = require("cors")
app.use(cors())
Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Thank you Sir, Bt it is kinda weird that when directly writing url string to fetch as parameter it does not work. Probably URL class adds additional instances which makes it work. – Selim Mıdıkoğlu Jun 02 '20 at 03:05