0

I'm doing some basic javascript/html development on my MacOs and am requesting a API to populate some fields and I get the error below.

I'm running Server version: Apache/2.4.56 (Unix) as a web server.

Origin http://127.0.0.1 is not allowed by Access-Control-Allow-Origin. Status code: 200

JS to pull API and populate

function loadHITS() {

  fetch(api_url)
  .then((res) => res.json())
  .then((data) => {
      console.log(data);
      document.getElementById('Count').innerHTML = data;
  });
  
}

I've tried adding this in my httpd.conf file but its not solving the issue.

<Directory /var/www/html> ... Header set Access-Control-Allow-Origin "*" ...

  • Some answers on this question that should likely set you on the right path https://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin – Craig Aug 11 '23 at 04:06

1 Answers1

0

try this, this may be works

In your API server code add the Access-Control-Allow-Origin header to allow requests from any origin like below:

const express = require('express');
const app = express();

// Allow cross-origin requests
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    // Other headers and logic
    next();
});

// Handle API routes and responses
// ...

app.listen(3000, () => {
    console.log('API server is running on port 3000');
});
  1. Keep the sama JavaScript code for fetching and populating data as you have now.
  2. You don't need to modify your Apache server's httpd.conf for this issue. Remove the Header set Access-Control-Allow-Origin "*" directive from your Apache configuration.

Make sure your API server is running and accessible from your localhost, and that the api_url you're using in your JavaScript code points to the correct API endpoint.

These steps should resolve the cross-origin issue you were facing.

#Apache-Age

saima ali
  • 133
  • 9
  • Awesome! This worked!! Thanks! Now do I remove this after testing on my local host or is it ok to leave it, any security concerns? – Brian Kissler Aug 12 '23 at 02:36
  • no please don't remove, Thanks for voting and glad to know it worked.... it may help someone else – saima ali Aug 12 '23 at 07:56