简体   繁体   English

如何将输入的文本字段保存到Javascript对象文字中的name属性?

[英]How to save input from text field to name property in a Javascript object literal?

assistant.parsePostParams((params) => {
    let message = {
        name: "anon",
        body: params.body,
        when: new Date().toISOString()
    }
}

Let me preface a little first... This was all built in a classroom working with partners as a project for servers and clients. 首先让我作为序幕...这全都建立在与合作伙伴一起作为服务器和客户端项目的教室中。 I think part of why the code has a lot of issues is because I've thrown my hands up in frustration at it and have just been writing anything and trying it then either not removing all of it properly or commenting it out also not properly. 我认为代码中存在很多问题的部分原因是因为我对此感到沮丧,并且只是写了什么然后尝试尝试,然后要么未正确删除所有代码,要么也未正确注释掉它。 At one point everything worked, but am now trying to add to it. 某一时刻一切正常,但现在正在尝试添加。 There was a spec.js we were running tests from using jasmine--node. 我们通过使用茉莉花节点运行了一个spec.js. Anyway thanks again Also this is my first time posting so please be gentle. 无论如何再次感谢,这也是我的第一次发贴,请保持温柔。 This isn't my complete code obviously, but I am wondering how to change the code so that "anon" can be something that is input by the user. 显然,这不是我的完整代码,但是我想知道如何更改代码,以便“ anon”可以是用户输入的内容。 Currently, I am using 'body' in the client and getting messages input as I want them to... sort of. 目前,我在客户端中使用“ body”,并根据需要输入消息。 But I can't figure out how to input a username and save it as the name. 但是我不知道如何输入用户名并将其保存为名称。 This is the part of the code I thought is most relevant to the issue. 这是我认为与该问题最相关的代码部分。 I have 2 main files, my client and my server, and 3 objects. 我有2个主要文件,我的客户端和我的服务器以及3个对象。 So it would be sort of problematic to link everything here. 因此,将所有内容链接到此处会有些问题。 Any help would be appreciated, thank you! 任何帮助,将不胜感激,谢谢!

here is the entire index.html. 这是整个index.html。 its a work in progress... please dont laugh 它正在进行中...请别笑

<!DOCTYPE html>
<html lang- "en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
    <meta http-equiv="X-UA-Compatible" content="ie-edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <h1>Chat</h1>

    <div class="pickRoomDiv">
        <button id="pickRoom">Enter Room</button>
        <select>
            <option title="selectRoom">Select Room</option>
            <option title="chatRoom">chat room</option>
        </select>
    </div>

    <div id="form-input">
        <form id="name-form" action="/" method="POST">
            <input type="text" placeholder="Enter Username">
            <input type="submit" name="body" value="Submit Username">
        </form>
    </div>

    <div id="form-input" class="submitDiv">
        <form id="chat-form" id="newMessageInput" action="chat" method="POST">
            <input type="text" name="body" placeholder="Enter Message">
            <input type="submit" value="Submit Message">
        </form>
        <button id='getAllNow' action='chat' method='GET'>Get All Messages</button>
        <!-- <form id="getMessages" action="chat" method="GET"></form> -->

    </div>
    <div id='chat-log'></div>



    <script>
        let chatForm = document.getElementById('chat-form')
        let chatLog = document.getElementById('chat-log')
        let getMessages = document.getElementById('getAllNow')
        let submitName = document.getElementById('name-form')
        let since
        let messages = []

        chatForm.addEventListener('submit', (event) => {
            // prevents the event from performing the default function.
            event.preventDefault();
            let inputElement = chatForm.querySelector('input[name=body]')
            // let inputElement = document.getElementById('newMessageInput') 

            let message = inputElement.value

            // the function below gets all of the parameters from the URL so I can use them later.
            let params = new URLSearchParams();
            params.append('body', message)
            fetch('/chat', {
                method: 'POST',
                body: params,

            })
                .then((response) => response.json())
                .then((messages) => {
                    chatLog.innerHTML = messages.map(message => message.body).join('<br>')


                })

        })

        getMessages.addEventListener('click', (event) => {

            fetch('/chat', {
                method: 'GET',

            })
                .then((response) => response.json())
                .then((messages) => {

                    let latestFormatChatMessages = messages.map((message) => {

                        let newPTag = (`<p class="fancy"> <strong>${message.body}</strong></p> <p class="when">${message.when}</p> <p class="fancy"><strong>${message.name}</strong> </p>`)
                        return newPTag
                    })
                    chatLog.innerHTML = latestFormatChatMessages.join('<br>')
                    submitName.value
                })

        })

I am getting name back as undefined. 我将名称重新定义为未定义。 here is the server code. 这是服务器代码。

const http = require('http');
const mime = require('mime-types');
const Assistant = require('./assistant');
const House = require('./lib/house');
const port = process.env.PORT || 5000;
let messages = [];
let house = new House();

http.createServer(handleRequest).listen(port);
console.log("Listening on port " + port);

function handleRequest(request, response) {
  let assistant = new Assistant(request, response);
  let path = assistant.path;
  let [_, base, roomId] = path.split('/')[1]

  if (roomId = "") {
    roomId === 'general'
  }
  roomId = roomId || 'general'

  function sendMessages(messages) {
    let data = JSON.stringify(messages);
    let type = mime.lookup('json');
    assistant.finishResponse(type, data);
  }
  // function submitName(messages) {
  //   let data = JSON.stringify(messages);
  //   let type = mime.lookup('json');
  //   assistant.finishResponse(type, data)
  // }

  try {
    let data = JSON.stringify(messages);
    let type = mime.lookup('json');
    if (path === '/') {
      assistant.sendFile('index.html');

    } else if (path === '/chat') {
      console.log(request.method)

      if (request.method === 'GET') {
        let room = house.roomWithId(roomId)
        let messages = room.messagesSince(0)
        sendMessages(messages)

      } else {
        console.log('Parsing the POST');
        assistant.parsePostParams((params) => {
          let message = {
            body: params.body,
            when: new Date().toISOString()

          }


          messages.push(message);

          assistant.finishResponse(type, data);
          console.log(type)

          house.sendMessageToRoom(roomId, message);


        })
      }

    } else {
      let fileName = path.slice(1);
      assistant.sendFile(fileName)
    }
  } catch (error) {
    assistant.sendError(404, "Error: " + error.toString());
  }
}


// function handleRequest(request, response0 {
//   let url = require('url')
// })

        // console.log('Parsing the GET')
        // let data = JSON.stringify(messages);
        // let type = mime.lookup('json');
        // assistant.finishResponse(type, data);

There are a lot of issues with your code. 您的代码有很多问题。 Looking at your code it seems like you do not have clear idea of how server-client architecture works. 查看您的代码,似乎您对服务器-客户端体系结构的工作方式尚无明确的想法。 It seems like you are trying to make a chat application. 似乎您正在尝试制作聊天应用程序。 You need to take care of three things here. 您需要在这里照顾三件事。

Client: Takes name of chatroom, username and message. 客户:获取聊天室的名称,用户名和消息。 Then on press of a button sends the data to server by making a POST request and waits for response. 然后,按下按钮,通过发出POST请求将数据发送到服务器,然后等待响应。

Server: Receives the data sent by client and saves it in a database. 服务器:接收客户端发送的数据并将其保存在数据库中。 If save is successful, server sends back a success response. 如果保存成功,服务器将发送回成功响应。 This response may also include the saved row in database. 此响应还可能包括数据库中保存的行。 If save is unsuccessful, and error message should be returned. 如果保存失败,则应返回错误消息。

Client: Receives the response. 客户端:接收响应。 If the response is success, then updates the chat list. 如果响应成功,则更新聊天列表。 If response is an error, communicate the error message to user. 如果响应是错误,则将错误消息传达给用户。

I fixed the client a little bit so that you get the required information and send it to server. 我固定了一点客户端,以便您获得所需的信息并将其发送到服务器。

Client 客户

 const sendMessage = document.getElementById('send-message'); const username = document.getElementById('username'); const message = document.getElementById('message'); const chatLog = document.getElementById('chat-log'); const getMessages = document.getElementById('get-all-messages'); const messages = []; sendMessage.addEventListener('click', (e) => { const d = new Date().toISOString(); alert("Username: " + username.value + '\\n' + "Message: " + message.value + '\\n' + "When: " + d); // the function below gets all of the parameters from the URL so I can use them later. fetch('/chat', { method: 'POST', body: { body: message.value, name: username.value, when: d, }, }) .then((response) => response.json()) .then((messages) => { chatLog.innerHTML = messages.map(message => message.body).join('<br>') }); }); getMessages.addEventListener('click', (e) => { fetch('/chat', { method: 'GET', }) .then((response) => response.json()) .then((messages) => { let latestFormatChatMessages = messages.map((message) => { return `<p class="fancy"><strong>${message.body}</strong></p> <p class="when">${new Date(message.when)}</p><p class="fancy"><strong>${message.name}</strong> </p>`; }) chatLog.innerHTML = latestFormatChatMessages.join('<br>'); }); }); 
 <!DOCTYPE html> <html lang- "en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> <meta http-equiv="X-UA-Compatible" content="ie-edge"> <title>Document</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <h1>Chat</h1> <div class="pickRoomDiv"> <button id="pickRoom">Enter Room</button> <select> <option title="selectRoom">Select Room</option> <option title="chatRoom">chat room</option> </select> </div> <div id="form-input"> <input id="username" type="text" placeholder="Enter Username"> <input id="message" type="text" placeholder="Enter Message"> <button id="send-message"> SEND </button> </div> <br> <br> <button id='get-all-messages'>Get All Messages</button> <div id='chat-log'></div> </body> </html> 

I would suggest that you start off by following a tutorial that teaches you key concepts. 我建议您从遵循一个教导您关键概念的教程开始。 There is an option to use sockets . 有一个使用套接字的选项。 Sockets help in real-time messaging. 套接字有助于实时消息传递。

Following medium tutorial should help you understand the concepts of programming and code formatting. 后续的中级教程应有助于您理解编程和代码格式化的概念。

Chat app tutorial 聊天应用程序教程

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

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