【问题标题】:How to send React form data to backend express server如何将 React 表单数据发送到后端快递服务器
【发布时间】:2020-09-25 21:30:48
【问题描述】:

我已经制作了这个反应表单,并希望将候选对象发送到后端快速服务器,我想在其中控制台记录候选对象。我已检查表单是否正确输入。我正在使用 axios 向 express 后端发送 post 请求。

import React, { Fragment, useState } from "react";
import axios from "axios";

const Form = () => {
  const [candidate, setCandidate] = useState({
    fullName: "",
    phoneNumber: 0,
    email: "",
    gitProfile: "",
    linkToResume: "",
    designation: "",
    interest: "",
  });

  const onChange = e =>
    setCandidate({ ...candidate, [e.target.name]: e.target.value });

  const onSubmit = e => {
    e.preventDefault();

    axios
      .post("http://localhost:5000/", {
        candidate,
      })
      .then(res => {
        console.log(res, candidate);
      });
  };
  const designationOptions = [
    "--select option--",
    "Graphic Designer",
    "Full Stack Developer",
    "Project Manager",
    "SEO and Digital Marketing",
  ];

  return (
    //form input code
  );
};

export default Form;

这是后端快递服务器代码。

const express = require("express"),
  bodyParser = require("body-parser");
(app = express()), (port = process.env.PORT || 5000), (cors = require("cors"));

app.use(
  cors({
    origin: "http://localhost:3000",
    credentials: true,
  })
);

app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

app.get("/", function (req, res) {
  console.log(req.body);
});

app.listen(port, () => console.log(`Backend server live on ${port}`));

我想发送候选对象和 console.log 对象,但我收到 404 错误。 我在父目录下的两个不同文件夹中有此设置。

【问题讨论】:

    标签: node.js express axios


    【解决方案1】:

    您在使用POST 发送请求时使用app.get。 尝试将app.get 切换为app.post

    【讨论】:

    • 这解决了我的问题。太感谢了。我想将电子邮件凭据传递给同一目录中的另一个文件以进行进一步处理。你能帮我解决这个问题吗?
    猜你喜欢
    • 2021-05-01
    • 2019-05-27
    • 2019-06-06
    • 1970-01-01
    • 2020-01-02
    • 2019-03-05
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多