I’m learning how to work with Kotlin and Javascript, and right now, I’m trying to load a .json file that’s present on the same server the website itself is hosted from.
How would I go about this? There’s a JSON object but the documentation doesn’t really say how to use it.
Right, so I can use it to parse a string into a JSON object graph, the problem I’m having is that I don’t undertstand where to get this string from, ie. how do I read the file?
And how would this work for a file on the same site? Trying to fetch "res/test.txt" results in the following error: Main.kt:5 Fetch API cannot load file:///D:/Programming/Kotlin/SiteTest/web/res/test.txt. URL scheme must be "http" or "https" for CORS request.
Thats a browser safety feature. Imagine any site can read any file on your device thats bad for security.
You have to serve files with some kind of server.
For tutorial porpoises there are simplistic web servers built in node.js/python/ IDEA itself and many others.
If you are using IDEA try opening html file with IDE it will spin up internal server and serve whole folder contents. You can access files in there with relative paths in html.
This won’t work with filesystem, it’s not Kotlin constraint it’s rather because of XSS protection in browsers. You should serve your HTML, JS and files from HTTP server.
Ah but using relative paths like that will start working when I host them on an actual server?
I didn’t even think about the security implications this would have if it actually worked . The build-in IDEA web server will do fine for now, thanks for the suggestion @Konstantin-Khvan.
Yes, this should work. res/test.txt will load file relative to a HTML page you are sending request from. /res/test.txt will load file from the current host and corresponding path (for example, http://localhost:8080/res/test.txt).
I know it’s not strictly Kotlin-related any more, but is there a way to start the build-in Idea server as a run configuration? Otherwise I’ll have to resort to one of the web serving one-liners .