简体   繁体   中英

Javascript - Send User Input from front-end to back-end server

I have an input field where the user enters a location, once the submit button is pressed, I can capture the data that the user entered as newLocation . However, I need to send this data to the back-end server and I am not sure how. I guess one way is to use axios.post and axios.get - but I am not quite sure how to implement that. See both front-end and back-end code below:

Front-end :

import store from "../src/store";
import axios from "axios";

const RenderButton = () => {
  async function captureText() {
    const locationName = document.getElementById("locationName");
    let newLocation = locationName.value;
    store.dispatch({ type: "locationUpdate", payload: newLocation });
  }
  return (
    <div id="submit">
      <h2>Enter Location</h2>
      <input type="text" id="locationName" />
      <button id="submitButton" onClick={captureText}>
        Submit Location
      </button>
    </div>
  );
};

export default RenderButton;

Back-end :

const path = require("path");
const axios = require("axios");

const app = express();

app.use("/dist", express.static(path.join(__dirname, "dist")));
app.use("/public", express.static(path.join(__dirname, "public")));

app.get("/", async (req, res, next) =>
  res.sendFile(path.join(__dirname, "index.html"))
);

Axios would not be needed on the backend. You just need to set up a route in express, just like the / one that returns the html. It can take request parameters such as form data. Something like this:

app.get('/endpoint', function (req, res) {
  console.log(req.body)
})

See for formdata parsing: https://stackoverflow.com/a/38763341/13357440 Also: https://expressjs.com/en/guide/routing.html

As for the frontend, many options exist that can send a request and get a response without redirecting. XMLHttpRequest (ajax) is one of the more popular ones. https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started#step_3_%E2%80%93_a_simple_example

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