Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Use fetch on localhost with URL parameters [closed]

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.

like image 603
Roymunson Avatar asked Jan 12 '19 23:01

Roymunson


1 Answers

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())
like image 185
Roymunson Avatar answered Oct 20 '22 02:10

Roymunson