简体   繁体   English

NodeJS - EJS 接收数据客户端

[英]NodeJS - EJS receive data client side

I have this NodeJS router file, which uses Express and EJS.我有这个 NodeJS 路由器文件,它使用 Express 和 EJS。 I'm trying to send data from the server to the client side.我正在尝试将数据从服务器发送到客户端。

const express = require('express');
const router = express.Router();

router.get('/test', (req, res) => {
    let myObj = {
        name: 'Bob',
        age: '31'
    }
    res.render('test', {
        myObj: JSON.stringify(myObj)
    })
})

module.exports = router;

In my test.ejs file, I have the following code:在我的test.ejs文件中,我有以下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <script>
        console.log('<%= myObj %>')
    </script>
</head>
<body>
    <%= myObj %>
</body>
</html>

In the body tags, the object is displayed.在正文标签中,显示了 object。 But when I try use JS to console log the object, this text is printed out instead: text in console log .但是当我尝试使用 JS 来控制台记录 object 时,会打印出以下文本:控制台日志中的文本。 What's the issue and how do I fix it?有什么问题,我该如何解决?

You want to use the unescaped tag for this.您想为此使用未转义的标签。 See tags in the documentation :请参阅文档中的标签:

  console.log('<%- myObj %>')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM