簡體   English   中英

Javascript - 將用戶輸入從前端發送到后端服務器

[英]Javascript - Send User Input from front-end to back-end server

我有一個用戶輸入位置的輸入字段,一旦按下提交按鈕,我就可以捕獲用戶輸入為newLocation的數據。 但是,我需要將此數據發送到后端服務器,但我不確定如何。 我想一種方法是使用 axios.post 和 axios.get - 但我不太確定如何實現。 請參閱下面的前端和后端代碼:

前端

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;

后端

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。 你只需要在 express 中設置一個路由,就像返回 html 的/一樣。 它可以接受請求參數,例如表單數據。 像這樣的東西:

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

有關表單數據解析,請參閱: https://stackoverflow.com/a/38763341/13357440另請參閱: https://expressjs.com/en/guide/routing.ZFC35FDC70D5FCC7A6D

至於前端,有許多選項可以發送請求並獲得響應而無需重定向。 XMLHttpRequest(ajax)是比較流行的一種。 https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started#step_3_%E2%80%93_a_simple_example

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM