Run app
cd
into the02_static_files/
dir:cd 02_static_files/
Fire up R:
R
Restore package dependencies:
::restore() renv
Once done, exit R.
index.R
is the entry point. To start the app, run this on the terminal:Rscript index.R
Explanation
This app starts a server and listens on port 3000 for connections.
It has a single endpoint:
Now that the app is running, navigate to these links in your browser:
To serve static files such as images, CSS files, JavaScript files etc., use the app$static()
method.
For example, let’s say this is your directory structure:
|- index.R
|- public/
|- index.html
|- about.html
|- image.jpg
|- css
|- styles.css
|- index2.R
|- main.js
/public
To make the files accessible at the path /public
, you’d do this:
$static(path = "public", uri = "public") app
path
specifies the static directory.uri
defines the path ambiorix should serve the static files from.
So now you’ll be able to do this in your app:
$get("/", \(req, res) {
app$send(
res"<h1>Hello everyone!</h1>
<img src='public/image.jpg'/>"
) })
By making the public/
folder static, any resource placed there can be accessed via the browser eg. http://localhost:3000/public/image.jpg
/your-own-path
You can make static content accessible via your own custom path too.
For example, let’s use /static
this time:
$static(path = "public", uri = "static") app
Then in your code you’ll use this:
$get("/", \(req, res) {
app$send(
res"<h1>Hello everyone!</h1>
<img src='static/image.jpg'/>"
) })
Keep this in mind:
- All static files are exposed and can be accessed via the browser. DO NOT put sensitive files there.
- You can also use htmltools tags instead of writing html strings.
Basic routing
Learn the ✨basics of routing✨.