iT邦幫忙

1

ejs <a> 寫法問題 window.location.origin

hyc 2019-07-16 17:58:553829 瀏覽
  • 分享至 

  • xImage

大家好~
我在寫ejs的頁面, 因為上線及測試環境的主機不同, 想用 window.location.origin去取得主機網址

但原html不曉得怎麼套用進去

<a href="http://localhost:3000/dashboard/client" target="_blank">
</a>

煩請大家幫幫我的幫~謝謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
dragonH
iT邦超人 5 級 ‧ 2019-07-16 18:58:36
最佳解答

ejs 是在 server 端 render html

所以我想是沒辦法取得 window 的

有點搞不太懂你的需求

如果你是要連到同個主機的頁面

html改成

<a href="/dashboard/client" target="_blank">
</a>

就可以了吧 /images/emoticon/emoticon19.gif

如果是要連到特定主機

就把 url 以變數的方式 render 出來

e.g.

app.js

...
const baseUrl = 'http://127.0.0.1:3000';
...

index.ejs

...
<a href="<%=`${baseUrl}/dashboard/client`%>" target="_blank">123</a>
...
看更多先前的回應...收起先前的回應...
hyc iT邦新手 5 級 ‧ 2019-07-17 16:52:12 檢舉
<a href="/dashboard/client" target="_blank">
</a>

這個寫法會直接變成 http:///dashboard/client

第二個寫法OK

但我是因為要隨著檔案的位置不同
才想說用 window.location.origin 去取得當下的主機位址
而不要寫死在 http://127.0.0.1:3000
但是用這個語法會出現
error log : window is not defined
用 location.origin
error log: location is not defined

謝謝你

dragonH iT邦超人 5 級 ‧ 2019-07-17 17:09:24 檢舉

我覺得是你寫法的問題唷

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>
    <p>EJS Welcome to <%= title %></p>
    <a href="/dashboard/client" target="_blank">link</a>
</body>
</html>

https://ithelp.ithome.com.tw/upload/images/20190717/20117259L6yaAh71Wh.png

hyc iT邦新手 5 級 ‧ 2019-07-18 16:54:34 檢舉

OK~發現問題盲點了! 謝謝大大

dragonH iT邦超人 5 級 ‧ 2019-07-18 16:57:12 檢舉

可以透露一下嗎XD

有點好奇
/images/emoticon/emoticon07.gif

0
marlin12
iT邦研究生 5 級 ‧ 2019-07-16 21:29:46

ejswindow.location.origin取得的主機網址,套用到連結上。
codepen

<% const domain = window.location.origin; %>

<a href="<%= domain + '/dashboard/client' %>" target="_blank">Dashboard</a>

其實,用javascript已經可以做到,不需要用ejs
codepen

<a href="javascript:redirect('/dashboard/client')">Dashboard</a>

<script>
  const domain = window.location.origin;
  
  function redirect(path) {
    const url = domain + path;
    console.log( url );
    //window.location.href = url;  // 在現在的視窗內開啟
    window.open( url, '_blank' );  // 在新的視窗內開啟
  }
</script>
hyc iT邦新手 5 級 ‧ 2019-07-18 16:55:12 檢舉

謝謝你!

我要發表回答

立即登入回答