Sending a CORS compliant fetch request from my locally hosted HTML page to my Node server [duplicate]

  cors, html, javascript, node.js

All I’m trying to do is spin up a barebones HTML page, send a fetch request from it that pings my little Node server, which in turn sends information back. However I’m running into CORS problems.

The Node server is hosted on port 3000.

let express = require('express');

let app = express();

app.get('/test', (req, res) => {
    res.send('hii!');
});

app.listen(3000, function() {
    console.log('listening');
});

The HTML file is hosted by the browser? I just click on it to open it from the file location, E/Code/HTMLFileFolder. So there’s no obvious server config for me to reach into, to adjust any headers. The most obvious solution to this would be to host this on a webserver and proxy the request, but that’s not an option right now. The fetch request looks like this.

<script>
  let getPosts = async () => {
    const url = "http://localhost:3000/test";
    const response = await fetch(url);
  
    console.log(response.json())
  }
 
  getPosts();
  </script>  

But when this code executes, I get

Access to fetch at 'http://localhost:3000/test' from origin 'null' 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.

How would ya’ll approach this?

Thanks!

Source: Ask Javascript Questions

LEAVE A COMMENT