简体   繁体   中英

What's the right way to get data from ReactJS front-end to NodeJS back-end?

How to correctly orginize ReactJS code in that way, that click-handler from client send data to back-end (Current URL and input value in field "body") (Twilio module)? Front-end:

<form>
    <input type="text"/>
    <button onClick={handler}>Send</button>
</form>

Back-end:

const accountSid = "account-Sid";
const authToken = "auth-token";
const client = require("twilio")(accountSid, authToken);

const SendMessage = client.messages
  .create({
    body: "text_here",
    from: "whatsapp:+@recipient",
    to: "whatsapp:+@reciever",
  })
  .then((message) => console.log(message.sid))
  .done();

module.exports = {
  SendMessage,
};

Pseudo-code in front-end:

import SendMessage from "../server/messageAPI/messageAPI";

const location = useLocation();
let value = "";

const handler = () => {
  SendMessage(location, value);
};
<form>
  <input type="text" value={value} />
  <button onClick={handler}>Send</button>
</form>;

I would do something like this

const SendMessageComponent = () => {
  const location = useLocation()
  const [message, setMessage] = useState("")
 
  const handleMessage = (event) => setMessage(event.target.value)
  const sendMessage = () => SendMessage(location, message)

  return (
    <>
      <input type="text" value={message} onChange={handleMessage} />
      <button onClick={sendMessage}>Send</button>
    </>
  )
}

You backend code -:

const accountSid = "account-Sid";
const authToken = "auth-token";
const client = require("twilio")(accountSid, authToken);

const theNumberYouBoughtFromTwilio = "123457696";

const SendMessage = (message, to) =>
  client.messages
    .create({
      body: `${message}`,
      from: `whatsapp:+${theNumberYouBoughtFromTwilio}`,
      to: `whatsapp:+${to}`,
    })
    .then((message) => console.log(message.sid))
    .done();

module.exports = {
  SendMessage,
};

Your frontend code:-

import React, { useState } from "react";
import SendMessage from "../server/messageAPI/messageAPI";

const App = () => {
  const [message, setMessage] = useState("");

  const messageHandler = async (e) => {
    e.preventDefault();
    console.log(message);
    await SendMessage(location, message); // incase sendmesssage is async call which makes sense
  };

  return (
    <div>
      <form>
        <input onChange={(e) => setMessage(e.target.value)} value={message} />
        <button onClick={messageHandler}>Send</button>
      </form>
    </div>
  );
};

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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