【问题标题】:Pass URL to front end from Node.js从 Node.js 将 URL 传递到前端
【发布时间】:2021-08-20 22:56:11
【问题描述】:

我正在为用户构建一个带有预先确定答案的聊天机器人。一些答案需要文本,这些文本将是可点击的 URL/重定向。使用这个https://developer.mozilla.org/en-US/docs/Web/API/URL/URL 作为参考。

如何以较短的方式将 URL 从我的节点服务器传递到我的前端应用程序?例如。 “点击这里

let url_one = new URL('https://www.google.co.uk/books/edition/Cotton_Candy/4smcwgEACAAJ?hl=en', 'Cotton Candy — Victoria Blakemore (2019)');

const Messages = [
    {
        message: `I couldn’t find what you’re looking for. Maybe try again but use vaguer search terms. This is also interesting by the way: ${url_one}`
    },

]

module.exports = Messages;

【问题讨论】:

  • 我没有收到你的问题。您想获得来自后端的答案吗?
  • 这完全取决于前端应用程序期望接收数据的格式。如果您正在编写前端,那么它可以是您想要设计或重用的任何数据格式。否则,您需要阅读文档和/或与前端作者合作。
  • 你只是问如何制作 HTML 链接?

标签: javascript node.js arrays variables url


【解决方案1】:

您错误地使用了URL constructor。第一个参数是url 的路径,然后是base。锚标记 (<a>) 的文本不是实际 URL 对象的一部分。您将需要自己的对象或数据结构来保存这些附加信息。

请看下面的例子:

const anchorTag = ({ text, href }) => `<a href="${href}">${text}</a>`;

const link = {
  text: 'Cotton Candy — Victoria Blakemore (2019)',
  href: new URL('books/edition/Cotton_Candy/4smcwgEACAAJ?hl=en', 'https://www.google.co.uk')
};

const Messages = [{
  message: `I couldn’t find what you’re looking for. Maybe try again but use vaguer search terms. This is also interesting by the way: ${anchorTag(link)}`
}];

//module.exports = Messages;

document.body.innerHTML = Messages[0].message; // Processed as raw HTML on the client

您也可以只传递 url 而不传递基础:

const link = {
  text: 'Cotton Candy — Victoria Blakemore (2019)',
  href: new URL('https://www.google.co.uk/books/edition/Cotton_Candy/4smcwgEACAAJ?hl=en')
};

这是在 React 客户端中使用 dangerouslySetInnerHTML 呈现原始 HTML 的方法:

// Server
const
  anchorTag = ({ text, href }) => `<a href="${href}">${text}</a>`,
  link = {
    text: 'Cotton Candy — Victoria Blakemore (2019)',
    href: new URL('books/edition/Cotton_Candy/4smcwgEACAAJ?hl=en', 'https://www.google.co.uk')
  },
  Messages = [{
    message: `I couldn’t find what you’re looking for. Maybe try again but use vaguer search terms. This is also interesting by the way: ${anchorTag(link)}`
  }];

// Client
const App = () => {
  return (
    <div
      dangerouslySetInnerHTML={{
        __html: Messages[0].message
      }}>
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

【讨论】:

  • 这对我不起作用。当我将链接传递到 React 前端时,它显示为纯文本并且不格式化为 HTML
  • @ib95 我在最后添加了一个 React 示例。
猜你喜欢
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 2012-11-12
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多