简体   繁体   English

有没有办法将 javascript object 转换为字符串?

[英]Is there a way to convert a javascript object to a string?

I am building a simple chat app and want to greet new users with a welcome mesage, but all i see is [object Object].我正在构建一个简单的聊天应用程序,并想用欢迎消息向新用户致意,但我看到的只是 [object Object]。 The connection is working.连接正常。 What to do?该怎么办?

This is the messages object that i am using to model the messages这是我正在使用的消息 object 到 model 消息

const generateMessage = (text) => {
    return {
        text,
        createdAt: new Date().getTime()
    }
}

module.exports = {
    generateMessage
}

Here is my connection这是我的连接

io.on("connection", (socket) => {
    console.log("New socket connection")

    socket.emit("message", generateMessage("Welcome to the chat"))
    socket.broadcast.emit("message", "A new user has joined",)

    socket.on("sendMessage", (message, callback) => {
        io.emit("message", message)
        callback()
    })
    socket.on("disconnect", () => {
        io.emit("message", "A user has left")
    })
})

And here is the html where i render the messages to the browser这是 html,我将消息呈现给浏览器

<body>
    Chat app

    <div id="messages"></div>

    <form id="message-form">
        <input name="message" placeholder="Message">
        <button>Send</button>
    </form>
    

    <template id="message-template">
            <p></p>
    </template>

    <script src="/socket.io/socket.io.js"></script>
    <script src="../chat/chat2.js"></script>
</body>

In your client (the html file) you should create the message accessing text property of object:在您的客户端(html 文件)中,您应该创建 object 的消息访问文本属性:

const htmlMessageText = messageObjReceivedFromSocket.text

Not pass the object itself.不传递 object 本身。

It'll easier help you if post how you handling the socket events on client.如果发布您如何在客户端处理套接字事件,它会更容易帮助您。

okay first thing that generateMessage function is not returning proper key value好的,generateMessage function 没有返回正确的键值的第一件事

 return {
        text: text,
        createdAt: new Date().getTime()
 }

and the second thing you are trying to render the whole object but you should render第二件事你试图渲染整个 object 但你应该渲染

socket.emit("message", generateMessage("Welcome to the chat").text)

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

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