How do I describe the relative path when I write the common processing of multiple pages in a website?

Asked 1 years ago, Updated 1 years ago, 398 views

Suppose you create a service with the following URL:
https://example.com/hoge-service/←This is the top screen
https://example.com/hoge-service/favorite
https://example.com/hoge-service/user/123456User Page
https://example.com/hoge-service/js/common.js
https://example.com/hoge-service/image/banner.png

https://example.com/hoge-service/ is the front page and never goes above it
https://example.com/hoge-service-help←This is not available

At this time, how do I create a relative path to any URL, such as /hoge-service/js/common.js, no matter which page I am viewing?

For example, <script src="./js/common.js"> is fine, but
The user page should say <script src="./../js/common.js">.
You can be careful when you write the template engine with only the script tag, but
Actually, when you call api on fetch from js, or
When accessing url (./image/banner.png) in the style sheet, or
When writing img tags in html, or
There are countless places to write paths, so it's hard to dynamically create them all on the server side.

Assume that the hoge-service portion is dynamically changed in the environment variable.
The server side is node+express+ejs, which has some freedom, but
I don't want to replace all paths in html css js dynamically when responding.

javascript html nodejs expressjs

2023-01-08 10:02

3 Answers

I've never tried it myself, and I've only looked it up a little this time, but besides absolute pass and relative pass,
There seems to be a description of the route-facing path.

Write the path with the domain name as the root and start with /.
If the absolute path of the interesting file is https://example.com/hoge-service/js/common.js, the route-facing path is /hoge-service/js/common.js.

reference:
Explain the absolute, relative, and route-relative paths in an easy-to-understand way! Get the image first!


2023-01-08 15:02

I don't specialize in the front end, but can I use this?

Introduction to Express.js from inexperience|static file-wiblok

node.js-EJS include file relative to project root-Stack Overflow


2023-01-08 23:56

Although it is extremely minor, HTML has had <base>: the base URL element of the document since 1.0.
In the example question, before <head> (before any other relative path appears),

<base href="/hoge-service/">

If you write , all relative paths on html css js are processed starting with /hoge-service/.

Note, however, that even the in-page anchors are interpreted as links to other pages, following the document's base URL, as noted in MDN.


2023-01-09 08:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.