Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  64] [ 6]  / answers: 1 / hits: 29346  / 5 Years ago, sat, january 12, 2019, 12:00:00

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.



More From » localhost

 Answers
30

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())

[#52778] Tuesday, January 8, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiasavannahw

Total Points: 448
Total Questions: 122
Total Answers: 113

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
;