6

I am quite a beginner with JavaScript and I am trying to write a script that checks whether a website, let's say https://example.comreturns 404 status code or 200, and depending on the result, I'll access it or not. I am doing this on front end side. I don't have a server side, as the website is a static one that does not use a database. I am doing this using XMLHttpRequest.

 url = $("#foo").attr("href")
    function UrlExists(ur)
    {
        var http = new XMLHttpRequest();
        http.open('GET', ur, true);
        http.setRequestHeader("Access-Control-Allow-Origin", "http, https");
        http.setRequestHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTONS");
        http.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
        http.send();
        console.log(http.status);
    }
    UrlExists(url)

The problem is when I run this script, the following Exception is being thrown:

Access to XMLHttpRequest at 'http://example.com' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

From what I read so far, it is rather CORS issue than JavaScript and I could not find a solution so far.

Can anybody help me with this issue and explain me why? I have checked other questions on SO and so far, I did not find a working solution. I am open to other solution too if there are any. Thank you so much!

I much appreciate your time!

UPDATE 1: Unfortunately, I am still struggling with this issue. I've read a lot about CORS policy, the problem is that I can't get how I should I can safely allow headers to be sent through request from my server to another one. The resources are: an HTML page and some JS code in it. As I have mentioned above, I am trying to send a request from my site to another one to check the status of that website, and if 404 pops, I want to redirect my user.

geekt
  • 1,979
  • 3
  • 10
  • 20
  • Hey, just curious, were you able to get it to work? Will fell happy to know that you could! – Rakesh Gupta Jun 27 '21 at 23:32
  • Hey! So happy to hear from you! Unfortunately, after a while, I gave up to that idea. I am thinking of trying one more time with my head clear. It is more of a gap of knowledge here. I tried with .htaccess file, but I am not using Apache Server and PHP. I need to read more about nginx. But you helped me a lot to understand the issue! – geekt Jul 03 '21 at 11:01

2 Answers2

5

You need to set the CORS header on your web server. It is disabled by default for security reasons.

For example, in Nginx, you may do

add_header Access-Control-Allow-Origin example.com;

In case you are using a hosting service that does not allow webserver config modification, you may add the required headers to .htaccess file in your as shown under. In other words, place it in the root of your project where you have your index.html. Also, change the permissions to 644.

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

References:

https://stackoverflow.com/a/20082724/2777988

https://blog.container-solutions.com/a-guide-to-solving-those-mystifying-cors-issues

Rakesh Gupta
  • 3,507
  • 3
  • 18
  • 24
  • hello Mr Rakesh. Thank you for your fast reply. Some great insights about CORS. But I have a problem: I do not have a backend to my website. I am doing everything like old fashion. I use only HTML, CSS and JS. No other framework. Is there a way to solve it on the client side? – geekt Jun 23 '21 at 19:17
  • In order to serve html, css, j's, you need a web server. Backend is a different thing. No mater what you have to have a web server – Rakesh Gupta Jun 24 '21 at 12:00
  • You need to understand that no one can access your website without a web server serving your static content, html, css, js. – Rakesh Gupta Jun 24 '21 at 12:42
  • Yes, you're right. My mistake. I'm having a webserver and I'm using WinSCP. So, the solution would be the create a js file that permits CORS policy. I'll give that a try. Thank you so much! – geekt Jun 24 '21 at 12:50
  • Solution would be to add the CORS headers to your webserver config httpd.conf or nginx.conf depends on what your are using. – Rakesh Gupta Jun 24 '21 at 19:22
  • The problem is that I don't have such configuration....... – geekt Jun 25 '21 at 13:26
  • Check my response above that details the use of .htaccess file – Rakesh Gupta Jun 25 '21 at 13:37
  • Hello! That's so good! I'm going to implement it right now. My problem is the following: As webserver, I am using WinSCP. Is it enough to just add .htaccess file with the code to it, or shall I connect it with the webpage that has the script? I much appreciate your time and support mr. Rakesh! – geekt Jun 25 '21 at 16:32
  • Just put the .htaccess in the same directory where you have index.html (main). Make sure that you set the permission of this .htaccess file 644. Also, it is .htaccess not htaccess. leading period is mandatory. – Rakesh Gupta Jun 25 '21 at 17:14
2

I'm using Flutter and Nodejs (in HEROKU), this worked for me:

FLUTTER:

//FLUTTER

...

    final headers = <String, String>{
      'Content-Type': 'application/json',
      "Access-Control-Allow-Origin": "*",
    };

  final resp = await http.post(//here we make the req

      Uri.parse(url), 
      body: convert.jsonEncode(body),
      headers: headers,
    );

///

SERVER NODEJS IN HEROKU:

///SERVER NODEJS IN HEROKU
const express = require('express');
const cors = require("cors"); //this is a library to config easily cors
const app = express();


app.use(express.json());
app.use(cors({ origin: true })); // enable origin cors

app.post('/',async(req,res)=>{
...

///

Then i solved mixed content (with heroku), and cors problem