繁体   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