Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-将用户输入从前端发送到后端服务器_Javascript - Fatal编程技术网

Javascript-将用户输入从前端发送到后端服务器

Javascript-将用户输入从前端发送到后端服务器,javascript,Javascript,我有一个输入字段,用户在其中输入一个位置,一旦按下submit按钮,我就可以捕获用户作为newLocation输入的数据。但是,我需要将这些数据发送到后端服务器,我不确定如何发送。我想一种方法是使用axios.post和axios.get,但我不太确定如何实现它。请参见下面的前端和后端代码: 前端: import store from "../src/store"; import axios from "axios"; const RenderButto

我有一个输入字段,用户在其中输入一个位置,一旦按下submit按钮,我就可以捕获用户作为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)
})
有关formdata解析,请参见: 此外:

至于前端,有许多选项可以发送请求并获得响应,而无需重定向。XMLHttpRequest(ajax)是比较流行的一种